How to print a date in a regular format?
To display a date in a human-readable format in Python, lean on the strftime
method from the datetime
module. Here's a quick snippet to show today's date in a common format:
You'll get an output like "2023-03-15"
, which is a neat year-month-day layout. Feel free to modify the "%Y-%m-%d"
pattern to customize your date look.
Now, on to more date transformations because one can never have enough ways to tell time.
Formatting date to your whims
Throughout your Python journey, you're likely to come across myriad date formats, and you'll need to be adaptable. Here's how you can suitably deal with common situations:
Looping through a list of dates
When you're dealing with multiple dates, loop through them and apply formatting:
Using formatted string literals (The Cool F-strings)
Python 3.6+ gifted us with f-strings, an eloquent way to embed expressions:
Adapting to locale
Dates can don the local language and culture attire using the locale settings:
Alternative representations via repr
repr(date)
offers a developer-focused alternative representation of the object, handy for debugging:
Leveraging strftime for Custom Formats
strftime
comes packed with a variety of format codes, offering us the freedom to dress up our date-time components as info-rich as we want:
Unleashing the datetime and time module duo
Using datetime
and time
module together brings additional formatting utilities, like handling time zones or dealing with epochs:
String formatting with the elegant .format()
method
Even the humble .format()
method can help date objects present themselves in a formatted manner:
Was this article helpful?