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

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org



















Copyright ยฉ Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap