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

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

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))


Got any Python Language Question?