software development, devops, and stuff
Tree lined path

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)

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.