How to Convert Python String to DateTime Object


In order to convert a string to DateTime object we will make use of the datetime module that supplies classes for manipulating dates and times.

from datetime import datetime

Next we make use of the date.strftime(string, format) method to get a string representation of the date string.

datetime.strptime('26 March 2023 1:00 AM', '%d %B %Y %I:%M %p')


Let's take a look at an example,

from datetime import datetime

str_date = '26 March 2023 1:00 AM'
date_format_str = '%d %B %Y %I:%M %p'

date_time_object = datetime.strptime(str_date, date_format_str)

print(date_time_object)
Output:

2023-03-26 01:00:00

Convert String to DateTime obejct in Python

Reference: https://docs.python.org/3/library/datetime.html#module-datetime

-




Have Questions? Post them here!