Convert JSON date string to Python datetime

Chris Dutrow picture Chris Dutrow · May 29, 2012 · Viewed 37.7k times · Source

When translating dates to JSON, javascript is saving dates in this format:

2012-05-29T19:30:03.283Z

However, I am not sure how to get this into a python datetime object. I've tried these:

# Throws an error because the 'Z' isn't accounted for:
datetime.datetime.strptime(obj[key], '%Y-%m-%dT%H:%M:%S.%f')

# Throws an error because '%Z' doesn't know what to do with the 'Z'
#  at the end of the string
datetime.datetime.strptime(obj[key], '%Y-%m-%dT%H:%M:%S.%f%Z')

I believe that javascript is saving the string in official ISO format, so it seems that there should be a way to get python's datetime.strptime() to read it?

Answer

Andrew Clark picture Andrew Clark · May 29, 2012

Try the following format:

%Y-%m-%dT%H:%M:%S.%fZ

For example:

>>> datetime.datetime.strptime('2012-05-29T19:30:03.283Z', '%Y-%m-%dT%H:%M:%S.%fZ')
datetime.datetime(2012, 5, 29, 19, 30, 3, 283000)

The Z in the date just means that it should be interpreted as a UTC time, so ignoring it won't cause any loss of information. You can find this information here: http://www.w3.org/TR/NOTE-datetime