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.py178 chars9 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.py20 chars2 lines
Other format codes can be used to specify different datetime strings.
gistlibby LogSnag