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

Advertisements
Try Out Code2care Dev Tools:

Advertisements

Advertisements
Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and software developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include learnings, tutorials, trouble-shooting steps, video tutorials, code snippets, how-to, blogs, articles, etc.

🎉 We are celebrating the 10th years of Code2care! Thank you for all your support!

We strongly support Gender Equality & Diversity.