I have to convert a timezone-aware string like "2012-11-01T04:16:13-04:00" to a Python datetime object.
I saw the dateutil module which has a parse function, but I don’t really want to use it as it adds a dependency.
So how can I do it? I have tried something like the following, but with no luck.
datetime.datetime.strptime("2012-11-01T04:16:13-04:00", "%Y-%m-%dT%H:%M:%S%Z")
As of Python 3.7,
datetime.datetime.fromisoformat()can handle your format:In older Python versions you can’t, not without a whole lot of painstaking manual timezone defining.
Python does not include a timezone database, because it would be outdated too quickly. Instead, Python relies on external libraries, which can have a far faster release cycle, to provide properly configured timezones for you.
As a side-effect, this means that timezone parsing also needs to be an external library. If
dateutilis too heavy-weight for you, useiso8601instead, it’ll parse your specific format just fine:iso8601is a whopping 4KB small. Compare that totpython-dateutil‘s 148KB.As of Python 3.2 Python can handle simple offset-based timezones, and
%zwill parse-hhmmand+hhmmtimezone offsets in a timestamp. That means that for a ISO 8601 timestamp you’d have to remove the:in the timezone:The lack of proper ISO 8601 parsing is being tracked in Python issue 15873.