How to convert Python's .isoformat() string back into datetime object

Python 3.7+

As of Python 3.7 there is a method datetime.fromisoformat() which is exactly the reverse for isoformat().

Older Python

If you have older Python, then this is the current best "solution" to this question:

pip install python-dateutil

Then...

import datetime
import dateutil

def getDateTimeFromISO8601String(s):
    d = dateutil.parser.parse(s)
    return d

Try this:

>>> def gt(dt_str):
...     dt, _, us = dt_str.partition(".")
...     dt = datetime.datetime.strptime(dt, "%Y-%m-%dT%H:%M:%S")
...     us = int(us.rstrip("Z"), 10)
...     return dt + datetime.timedelta(microseconds=us)

Usage:

>>> gt("2008-08-12T12:20:30.656234Z")
datetime.datetime(2008, 8, 12, 12, 20, 30, 656234)