datetime to string in python

To convert a datetime object to a string in Python, you can use the strftime method. This method allows you to create a string representation of a datetime object based on a specified format.

Here's an example:

main.py
import datetime

# create a datetime object
my_datetime = datetime.datetime(2021, 8, 27, 14, 30, 0)

# convert the datetime object to a string
my_string = my_datetime.strftime("%Y-%m-%d %H:%M:%S")

# print the string
print(my_string)
234 chars
11 lines

Output:

main.py
2021-08-27 14:30:00
20 chars
2 lines

In the example above, we first create a datetime object representing August 27th, 2021 at 2:30 PM. We then use the strftime method to create a string representation of the datetime object using the format "%Y-%m-%d %H:%M:%S". This format specifies that the string should include the year, month, and day separated by dashes, followed by the time in hours, minutes, and seconds separated by colons. Finally, we print the resulting string.

gistlibby LogSnag