Python Language Date and Time Parsing a string into a timezone aware datetime object


Python 3.2+ has support for %z format when parsing a string into a datetime object.

UTC offset in the form +HHMM or -HHMM (empty string if the object is naive).

Python 3.x3.2
import datetime
dt = datetime.datetime.strptime("2016-04-15T08:27:18-0500", "%Y-%m-%dT%H:%M:%S%z")

For other versions of Python, you can use an external library such as dateutil, which makes parsing a string with timezone into a datetime object is quick.

import dateutil.parser
dt = dateutil.parser.parse("2016-04-15T08:27:18-0500")

The dt variable is now a datetime object with the following value:

datetime.datetime(2016, 4, 15, 8, 27, 18, tzinfo=tzoffset(None, -18000))