How to Convert String to Datetime in Python?
To convert a string to datetime in Python, you can use the datetime.strptime() method. Here is an example:
from datetime import datetime
# create a string representing a date
date_string = '2021-09-01 12:30 PM'
# convert the string to datetime format
date_time = datetime.strptime(date_string, '%Y-%m-%d %I:%M %p')
print(date_time)
In this example, we import the datetime module and create a string that represents a date. Then, we use the strptime() method to convert the string to datetime format. The first argument of the method is the string we want to convert, and the second argument is the format of the string. In this case, the format is '%Y-%m-%d %I:%M %p', which corresponds to the year, month, day, hour, minute, and am/pm format. Finally, we print the datetime object.