All Courses

How to Parsing a string into a datetime object?

By Albert, 2 years ago
  • Bookmark

How to convert string object into datetime object in python.?

2 Answers

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

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

datetime.datetime(2021, 4, 15, 8, 27, 18, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=68400)))

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("2021-04-15T08:27:18-0500")

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

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


from datetime import datetime
datetime_string = 'Oct 1 2016, 00:00:00'
datetime_string_format = '%b %d %Y, %H:%M:%S'
datetime.strptime(datetime_string, datetime_string_format)
# datetime.datetime(2016, 10, 1, 0, 0)

Your Answer


How To Land a Job in Data Science?

Feb 9th (7:00 PM) 184 Registered
More webinars

Related Discussions

Running random forest algorithm with one variable

View More