How do I translate an ISO 8601 datetime string into a Python datetime object?
Since Python 3.7 and no external libraries, you can use the fromisoformat function from the datetime module:
datetime.datetime.fromisoformat('2019-01-04T16:41:24+0200')
Python 2 doesn't support the %z
format specifier, so it's best to explicitly use Zulu time everywhere if possible:
datetime.datetime.strptime("2007-03-04T21:08:12Z", "%Y-%m-%dT%H:%M:%SZ")
I prefer using the dateutil library for timezone handling and generally solid date parsing. If you were to get an ISO 8601
string like: 2010-05-08T23:41:54.000Z
you'd have a fun time parsing that with strptime, especially if you didn't know up front whether or not the timezone was included. pyiso8601
has a couple of issues (check their tracker) that I ran into during my usage and it hasn't been updated in a few years. dateutil, by contrast, has been active and worked for me:
from dateutil import parser
yourdate = parser.parse(datestring)