convert string to datetime in python

In Python, we can convert a string to a datetime object using the datetime module. We first need to specify the format of the string using a series of codes to represent the different parts of the datetime. Here's an example:

main.py
from datetime import datetime

date_string = "2021-07-15 12:30:45"
format = "%Y-%m-%d %H:%M:%S"

datetime_object = datetime.strptime(date_string, format)

print(datetime_object)
178 chars
9 lines

In this example, we start by importing the datetime module. We then specify the string we want to convert to a datetime object, along with the format of the string using the %Y-%m-%d %H:%M:%S codes.

Next, we use the strptime() method of the datetime module to parse the string and return a datetime object. Finally, we print the datetime object using the print() function.

Output:

main.py
2021-07-15 12:30:45
20 chars
2 lines

Other format codes can be used to specify different datetime strings.

gistlibby LogSnag