Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Date/Time Formatting

I am working with an API that is returning a JSON string that contains the following date/time in it:

2013-03-14T14:15:23-07:00

I get the date and the time, down to the second. But the last 5 characters are confusing me. I'm guessing that's a UTC offset. (mountain time) What i can't figure out how to do is to compare the above string to a date/time in python. The T is also throwing me off.

How do I encode a python date/time string to match the above?

like image 580
Matt Keller Avatar asked Jun 29 '26 20:06

Matt Keller


2 Answers

If you use the python-dateutil library (https://crate.io/packages/python-dateutil/) you can convert that value to a datetime.

>>> dateutil.parser.parse('2013-03-14T14:15:23-07:00')
datetime.datetime(2013, 3, 14, 14, 15, 23, tzinfo=tzoffset(None, -25200))
like image 149
dirn Avatar answered Jul 02 '26 11:07

dirn


You are looking at ISO 8601 date format. You can use a package to parse it or do it yourself.

You can use datetime.strptime to parse:

>>> ts='2013-03-14T14:15:23-07:00'
>>> datetime.datetime.strptime(ts[0:-6],'%Y-%m-%dT%H:%M:%S')
datetime.datetime(2013, 3, 14, 14, 15, 23)

Then just add/subtract the time delta (for a 'naive' object):

>>> datetime.timedelta(hours=int(ts[-6:-3]))
datetime.timedelta(-1, 61200)

so:

>>> d=datetime.datetime.strptime(ts[0:-6],'%Y-%m-%dT%H:%M:%S')+datetime.timedelta(hours=int(ts[-6:-3]))
>>> d
datetime.datetime(2013, 3, 14, 7, 15, 23)

The tricky part is the TZ is optional and whether you add / subtract the time offset or set the timezone in the date object.

like image 36
dawg Avatar answered Jul 02 '26 11:07

dawg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!