Matt Keller
Matt Keller

Reputation: 347

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?

Upvotes: 3

Views: 1591

Answers (2)

dawg
dawg

Reputation: 103754

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.

Upvotes: 2

dirn
dirn

Reputation: 20719

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))

Upvotes: 2

Related Questions