How to Print a Date in a Regular Format?
As seen from the sample code, printing a single date object using print returns the desired regular format, such as "2008-11-22". However, when printing a list containing date objects, the result becomes "[datetime.date(2008, 11, 22)]". This is due to the unique characteristics of dates in Python.
Understanding Date Objects and Representations
Dates in Python are objects that possess two distinct string representations:
When Printing Lists Containing Date Objects
When printing lists containing date objects, it's essential to print the date objects themselves rather than the list container. This allows Python to use the regular string representation (str()) and eliminate the alternative representation (repr()).
Practical Application Using the Given Code
In the provided code, modifying it slightly allows for the printing of the dates in the list correctly:
import datetime mylist = [datetime.date.today()] # Print each date object individually, not the list for date in mylist: print(date)
Advanced Date Formatting with strftime()
Furthermore, you can customize the date format using the strftime() method. By passing a string pattern, you can specify how the date should be formatted. For instance, today.strftime('We are the %d, %b %Y') prints 'We are the 22, Nov 2008'.
Formatted string literals (since Python 3.6)
Since the introduction of formatted string literals, you can use the same format string as 'strftime()' directly in an f-string. For example, f"{datetime.datetime.now():'%Y-%m-%d'} prints "2023-03-08".
The above is the detailed content of How to Print Dates in Lists Without the `repr()` Representation in Python?. For more information, please follow other related articles on the PHP Chinese website!