Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

question from:https://stackoverflow.com/questions/10805589/convert-json-date-string-to-python-datetime

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
420 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...