How to Convert String to DateTime in Python


Python String to DateTime Example
Python String to DateTime Example

In order to convert a String to a DateTime object in Python we need to make use of the datetime module,

Example:
import datetime

string_date1 = '2022-03-22'
print(string_date1)

datetime_object1 = datetime.datetime.strptime(string_date1, '%Y-%m-%d')
print(datetime_object1)

string_date2 = '2022-03-22 10:10:12.345678'
print("String: " +string_date2)

datetime_object2 = datetime.datetime.strptime(string_date2, '%Y-%m-%d %H:%M:%S.%f')
print(datetime_object2)
Output:

2022-03-22
2022-03-22 00:00:00
String: 2022-03-22 10:10:12.345678
2022-03-22 10:10:12.345678

-

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


Author Info:

Rakesh (He/Him) is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. 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