3

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?

Matt Keller
  • 337
  • 4
  • 13
  • 1
    You're looking at [isoformat](http://docs.python.org/2/library/datetime.html#datetime.datetime.isoformat) – mgilson Feb 13 '13 at 05:38

2 Answers2

2

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))
dirn
  • 19,454
  • 5
  • 69
  • 74
  • Excellent! That's exactly what i needed. The only thing i'm stuck on now is trying to get the current datetime in an offset-aware format so i can compare the two. I'm still trying to wrap my head around how Python handles dates/times. – Matt Keller Feb 14 '13 at 02:05
  • 1
    You should be able to use `.replace(tzinfo=...)` on your datetime. Giving it a time zone makes it aware, `None` makes it naive. – dirn Feb 14 '13 at 05:25
2

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.

Community
  • 1
  • 1
dawg
  • 98,345
  • 23
  • 131
  • 206