Suppose I have the following datetime object:
>>> dt datetime.datetime(2015, 5, 13, 18, 5, 55, 320000, tzinfo=datetime.timezone(datetime.timedelta(-1, 61200)))
I can print this object in ISO 8601 format as follows:
>>> dt.isoformat() '2015-05-13T18:05:55.320000-07:00'
In Python 3.4, I can parse an ISO 8601 string string if I remove the colon in the time zone:
>>> import re >>> ts='2015-05-13T18:05:55.320-07:00' >>> tf="%Y-%m-%dT%H:%M:%S.%f%z" >>> tsm=re.sub(r'([+-]\d+):(\d+)$', r'\1\2', '2015-05-13T18:05:55.320-07:00') >>> tsm '2015-05-13T18:05:55.320-0700' >>> datetime.datetime.strptime(tsm, tf) datetime.datetime(2015, 5, 13, 18, 5, 55, 320000, tzinfo=datetime.timezone(datetime.timedelta(-1, 61200)))
In Python 2.7, the situation is worse since %z does not work as documented :
>>> tsm='2015-05-13T18:05:55.320-0700' >>> tf="%Y-%m-%dT%H:%M:%S.%f%z" >>> datetime.datetime.strptime(tsm, tf) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_strptime.py", line 317, in _strptime (bad_directive, format)) ValueError: 'z' is a bad directive in format '%Y-%m-%dT%H:%M:%S.%f%z'
Note that this is the same format string that works in Python 3.4.
Question: besides using dateutil (which works fine), is there any reasonable way to parse an ISO 8601 date string with a .strptime date or something else in the standard library?