
Problem –
You want to convert a string to datetime in python.
Solution –
To convert a string to datetime in python we can use the datetime.strptime() method in python. The strptime() method creates a date object from a given string.
Syntax –
datetime.strptime(string, format code)
Example –
In [1]: from datetime import datetime
In [2]: date_string = "6 july, 2022"
In [3]: type(date_string)
Out[3]: str
In [4]: date_object = datetime.strptime(date_string, "%d %B, %Y")
In [5]: date_object
Out[5]: datetime.datetime(2022, 7, 6, 0, 0)
Here,
%d – represents the day of the month.
%B – represents Months full name
%Y – represents year in four digit.
Let’s look at one more example.
In [9]: date_string = "6/07/2022 10:05:30"
In [10]: date_object = datetime.strptime(date_string, "%m/%d/%Y %H:%M:%S")
In [11]: date_object
Out[11]: datetime.datetime(2022, 6, 7, 10, 5, 30)
Format Code –


