Home >Backend Development >Python Tutorial >How to Format Dates for Printing in Python?
When appending a date to a list, the printed output appears as "[datetime.date(YYYY, MM, DD)]" instead of a simple "YYYY-MM-DD" format.
Dates in Python are objects. When printing, they have two representations:
To get a simple date string, cast the date object to a string using str(). This ensures that the regular representation is used when printing. Here's an example:
import datetime today = datetime.date.today() print(str(today)) # Prints "2008-11-22"
Alternatively, you can use the strftime() method to create a custom date format:
print(today.strftime('%Y-%m-%d')) # Prints "2008-11-22"
strftime() supports various format specifiers to customize the date format, such as:
You can also use string interpolation to directly format dates within strings:
print(f"Today is {today:%Y-%m-%d}")
The above is the detailed content of How to Format Dates for Printing in Python?. For more information, please follow other related articles on the PHP Chinese website!