Python date string to date object

If you have a date string and need to convert it into a date object, how can it be converted to a date object using Python?

Python includes within the datetime package a strptime function, here’s an example usage:

>>> import datetime
>>> datetime.datetime.strptime('2022-10-30T14:32:41Z', "%Y-%m-%dT%H:%M:%S%z")
datetime.datetime(2022, 10, 30, 14, 32, 41, tzinfo=datetime.timezone.utc)

Updated code for Windows

Recently I ran into an issue where a report was generated on Linux but I wanted to process it further on windows. The timezones don’t match up though and will cause issues. Let’s look at how to handle that.

from datetime import datetime, timezone, timedelta

date_str = "Oct 10, 2022 13:32:41 EST"

# Map abbreviations to UTC offsets
tz_offsets = {
    "EST": -5, "EDT": -4,
    "CST": -6, "CDT": -5,
    "MST": -7, "MDT": -6,
    "PST": -8, "PDT": -7,
    "UTC": 0,  "GMT": 0,
}

parts = date_str.rsplit(" ", 1)
dt_str, tz_abbr = parts[0], parts[1]

dt = datetime.strptime(dt_str, "%b %d, %Y %H:%M:%S")

offset = tz_offsets.get(tz_abbr)
if offset is not None:
    dt = dt.replace(tzinfo=timezone(timedelta(hours=offset)))

print(dt)

Now that it’s a date object and can be manipulated as needed.

If the date string you have doesn’t match this format, check out the format codes table to find the necessary directives.