Explain Codes LogoExplain Codes Logo

How to print a date in a regular format?

python
date-formatting
datetime-module
string-formatting
Anton ShumikhinbyAnton Shumikhin·Sep 14, 2024
TLDR

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:

from datetime import datetime # strftime likes to play dress-up print(datetime.now().strftime("%Y-%m-%d"))

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:

dates = [datetime(2023, 3, 15), datetime(2023, 4, 15), datetime(2023, 5, 15)] for date in dates: # Print them all, because we are democratic like that print(date.strftime("%d/%m/%Y"))

Using formatted string literals (The Cool F-strings)

Python 3.6+ gifted us with f-strings, an eloquent way to embed expressions:

# F-strings are the cool kids on the block print(f'{datetime.now():%d-%m-%Y %H:%M}')

Adapting to locale

Dates can don the local language and culture attire using the locale settings:

import locale from datetime import date # The date's wearing lederhosen today! locale.setlocale(locale.LC_ALL, 'de_DE') # This ain't your everyday date today = date.today() print(today.strftime('%A, %d. %B %Y'))

Alternative representations via repr

repr(date) offers a developer-focused alternative representation of the object, handy for debugging:

now = datetime.now() # This is not a date. It's a piece of art! print(repr(now))

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:

- `%Y`: Year with full fanfare (e.g., '2023') - `%m`: Month, but make it zero-padded (e.g., '04') - `%d`: Day of the month. Did I mention zero padding? (e.g., '01') - `%H`: Hour. You know the drill. (e.g., '14') - `%M`: Minute as zero-padded decimal (e.g., '33') - `%S`: Second. Yep, zeros are cool. (e.g., '47')

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:

import time from datetime import datetime print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) # Local time: "Hey, do you have the time?" print(datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')) # UTC time: "It's always teatime in London"

String formatting with the elegant .format() method

Even the humble .format() method can help date objects present themselves in a formatted manner:

print('Today is: {:%Y-%m-%d}'.format(datetime.now())) # The date humbly presents itself