How to print date in a regular format in Python?

When working with dates in Python, you might encounter different output formats depending on how you print them. Understanding the difference between string and object representations is crucial for proper date formatting.

Direct Date Printing

When you print a date object directly, Python automatically converts it to a readable string format ?

import datetime
today = datetime.date.today()
print(today)
2024-01-02

Date Objects in Lists

However, when you add date objects to a list and print the list, you see the object representation instead of the formatted string ?

import datetime
date_list = []
today = datetime.date.today()
date_list.append(today)
print(date_list)
[datetime.date(2024, 1, 2)]

Why This Happens

This occurs because datetime objects have two string representations:

  • String representation (__str__): Used by print() for readable output
  • Object representation (__repr__): Shows the object's technical format, used when objects are inside containers like lists

Converting to String Format

To get the readable date format in lists, explicitly convert the date object to a string using str() ?

import datetime
date_list = []
today = datetime.date.today()
date_list.append(str(today))
print(date_list)
['2024-01-02']

Alternative Approaches

You can also format dates using strftime() for custom formatting ?

import datetime
today = datetime.date.today()
formatted_date = today.strftime("%Y-%m-%d")
date_list = [formatted_date]
print(date_list)
['2024-01-02']

Conclusion

Use str() to convert date objects to strings when adding them to lists or other containers. This ensures consistent readable formatting instead of technical object representation.

Updated on: 2026-03-24T19:29:42+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements