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.py234 chars11 lines
Output:
main.py20 chars2 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