Formatting datetime objects in Python is done using format codes that are specific to date and time formatting. The strftime() method of a datetime object is used to format the date and time according to a given format string. Here's an example:
import datetimenow = datetime.datetime.now()print(now.strftime("%Y-%m-%d %H:%M:%S")) |
In this example, the strftime() method is used to format the current date and time as a string. The format string "%Y-%m-%d %H:%M:%S" specifies the format of the output string using format codes. Here's what each code means:
%Y: year with century as a decimal number%m: month as a zero-padded decimal number%d: day of the month as a zero-padded decimal number%H: hour (24-hour clock) as a zero-padded decimal number%M: minute as a zero-padded decimal number%S: second as a zero-padded decimal numberBy combining these format codes in a specific order, you can format the datetime object in any desired format. For example, to format the date as "March 15, 2023", you can use the following format string:
now.strftime("%B %d, %Y") |
In this format string, %B represents the full month name and %d represents the zero-padded day of the month.
You can find a full list of format codes in the Python documentation for the strftime() method.