To format datetime in Python, you can use the strftime method from the datetime module.
Here's an example that shows how to format a datetime object into a string:
main.py229 chars11 lines
In the above example, the strftime method is called on the dt datetime object to format it according to the specified format string "%Y-%m-%d %H:%M:%S". This format string defines the desired format, where %Y represents the year, %m represents the month, %d represents the day, %H represents the hour (24-hour format), %M represents the minute, and %S represents the second.
The output of the above code will be:
main.py20 chars2 lines
You can modify the format string to match your desired datetime format.
Note that strftime only works for formatting datetime objects into strings. If you have a string representing a datetime and want to parse it into a datetime object, you can use the strptime method instead.
main.py174 chars8 lines
The output will be:
main.py20 chars2 lines
gistlibby LogSnag