How can I convert a string to a datetime object in Python?
Antek N
antek n profile pic

In Python, you can convert a string to adatetime object using thestrptime() method from thedatetime module. Here's a detailed explanation of how to accomplish this:

1
2
3
4
5
6
7
8
9

from datetime import datetime

date_string = "2023-05-17"
format_string = "%Y-%m-%d"

datetime_object = datetime.strptime(date_string, format_string)

print(datetime_object)  # Output: 2023-05-17 00:00:00

In this example,datetime.strptime(date_string, format_string) converts the stringdate_string to adatetime object. Thestrptime() method takes two arguments: the date string to be converted and the format string that specifies the format of the date string. The format string uses special directives to define the format of the date string. In this case,%Y represents the four-digit year,%m represents the two-digit month, and%d represents the two-digit day. You can find a comprehensive list of directives in the Python documentation. Make sure that the format string matches the format of the date string exactly. If there's a mismatch, aValueError will be raised. If the date string includes time information, you can include the time format directives in the format string as well. Here's an example:

1
2
3
4
5
6
7
8
9

from datetime import datetime

datetime_string = "2023-05-17 09:30:45"
format_string = "%Y-%m-%d %H:%M:%S"

datetime_object = datetime.strptime(datetime_string, format_string)

print(datetime_object)  # Output: 2023-05-17 09:30:45

In this example, the format string%H:%M:%S represents the two-digit hour in 24-hour format, the two-digit minute, and the two-digit second. By using thestrptime() method, you can convert a string to adatetime object in Python. Ensure that the format string matches the format of the date string accurately to avoid any errors.