EN
Python - convert string to datetime
0
points
In this article, we would like to show you how to convert a string into datetime in Python.
Quick solution:
from datetime import datetime
datetime_object = datetime.strptime('Jun 11 2021 8:35PM', '%b %d %Y %I:%M%p')
print(datetime_object) # 2021-06-11 20:35:00
Where:
-
%b- abbreviated month name, -
%d- day of the month (01 to 31), -
%Y- year including the century, -
%I- hour (01 to 12), -
%M- minute -
%p- either am or pm according to the specified value.
Practical example
In this example, we convert a string into a datetime object with specified format using strptime() method.
from datetime import datetime
date_string = "Jun 11 2021 8:35PM"
date_format = "%b %d %Y %I:%M%p"
datetime_object = datetime.strptime(date_string, date_format)
print(datetime_object) # 2021-06-11 20:35:00
Output:
2021-06-11 20:35:00