Formatting Dates

Working with dates is a fundamental part of many Python applications — from logging events to formatting timestamps for reports or user interfaces. However, raw date and time objects often aren't human-friendly. That’s where date formatting comes in: it allows you to convert datetime objects into readable strings that fit your needs.

In this lesson, we'll dive deeply into how to format dates in Python using the datetime module, understand common formatting directives, and explore practical examples that you can immediately apply. Whether you're creating logs, displaying timestamps, or preparing data for export, mastering date formatting is a skill that will save you time and headaches.

Why Format Dates?

Raw date objects provide structured data, but they don't communicate the information in a way humans easily understand. For example:

2024-06-15 14:30:00

This is a typical datetime representation, but what if you need to display it as June 15, 2024 at 2:30 PM? Or maybe as 15/06/2024 for European audiences? Formatting puts you in control.

💡 Key Idea

Formatting dates converts date objects into strings with a desired layout, making them adaptable for different locales, reports, or user interfaces.

Getting Started: The datetime Module

Python’s built-in datetime module is your go-to for working with dates and times. Here’s how you can create a date object:

📌 Deep Dive: Creating a Date Object

PYTHON
from datetime import datetime

# Create a datetime object for June 15, 2024, 14:30
dt = datetime(2024, 6, 15, 14, 30)
print(dt)
Output
2024-06-15 14:30:00

By default, printing a datetime object shows the ISO 8601 format, which is standardized but not always ideal for display purposes. Let’s learn how to customize this output.

Formatting Dates with strftime()

The strftime() method is the heart of date formatting in Python. It stands for “string format time” and uses format codes (called directives) to specify how the date should be represented in string form.

strftime() syntax:

date_object.strftime(format_string)

Here, format_string is a combination of literal characters and format codes that tell Python how to build the output string.

Common Formatting Directives

Below is a table of some of the most useful directives you'll use for formatting dates and times:

Common strftime Directives
DirectiveOutput
%YYear with century (e.g., 2024)
%yYear without century (00-99)
%mMonth as zero-padded decimal (01-12)
%BFull month name (e.g., June)
%bAbbreviated month name (e.g., Jun)
%dDay of the month zero-padded (01-31)
%AFull weekday name (e.g., Monday)
%aAbbreviated weekday name (e.g., Mon)
%HHour (24-hour clock, 00-23)
%IHour (12-hour clock, 01-12)
%pAM or PM
%MMinute (00-59)
%SSecond (00-59)
%fMicrosecond (000000-999999)
%zUTC offset (e.g., +0000)
%ZTime zone name
%%Literal % character

Combining these lets you format dates exactly how you want. Let’s see it in action.

📌 Deep Dive: Formatting a Date to a Friendly String

PYTHON
from datetime import datetime

dt = datetime(2024, 6, 15, 14, 30)

# Format: June 15, 2024 at 2:30 PM
formatted_date = dt.strftime("%B %d, %Y at %I:%M %p")
print(formatted_date)
Output
June 15, 2024 at 02:30 PM

Notice how %B gives us the full month name, %d the day with leading zero, and %I the 12-hour format hour with %p for the AM/PM suffix.

Common Date Formatting Patterns

Depending on where your application is used or what you want to display, date formats can vary widely. Here are some common patterns and their Python format strings:

Common Date Format Patterns
Format ExamplePython Format String
2024-06-15 (ISO standard)%Y-%m-%d
15/06/2024 (European style)%d/%m/%Y
06/15/2024 (US style)%m/%d/%Y
Saturday, June 15, 2024%A, %B %d, %Y
2:30 PM%I:%M %p
14:30 (24-hour clock)%H:%M

Try experimenting with these patterns to see how flexible strftime is.

Formatting Today’s Date

Often, you want to format the current date and time dynamically. Python lets you get the current date/time with datetime.now().

📌 Deep Dive: Format Current Date and Time

PYTHON
from datetime import datetime

now = datetime.now()

# Example format: 2024-06-15 14:30:00
print(now.strftime("%Y-%m-%d %H:%M:%S"))

# Example format: Monday, June 15, 2024 at 02:30 PM
print(now.strftime("%A, %B %d, %Y at %I:%M %p"))
Example Output
2024-06-15 14:30:00
Saturday, June 15, 2024 at 02:30 PM

Advanced: Formatting with Time Zones

Working with time zones can be tricky, but Python’s datetime and zoneinfo modules simplify it. When your datetime object has timezone info, you can format the time zone name or offset using %Z and %z.

Example:

📌 Deep Dive: Formatting Dates with Time Zones

PYTHON
from datetime import datetime
from zoneinfo import ZoneInfo

dt = datetime(2024, 6, 15, 14, 30, tzinfo=ZoneInfo("America/New_York"))
print(dt.strftime("%Y-%m-%d %H:%M:%S %Z %z"))
Output
2024-06-15 14:30:00 EDT -0400

This prints the time zone abbreviation EDT and the numeric offset -0400. For full time zone support, ensure your date objects have timezone info.

⚠️ Important

If your datetime object is “naive” (without timezone info), %Z and %z will output empty strings.

Parsing Dates Back from Strings

While this lesson focuses on formatting dates to strings, it’s common to convert strings back to datetime objects using strptime(). This method uses the same format directives but in reverse.

Example:

📌 Deep Dive: Parsing a Date String

PYTHON
from datetime import datetime

date_string = "June 15, 2024 at 02:30 PM"
dt = datetime.strptime(date_string, "%B %d, %Y at %I:%M %p")
print(dt)
Output
2024-06-15 14:30:00

Understanding how to format and parse dates is a powerful combination for handling date/time data reliably.

Customizing Your Formats: Tips & Tricks

  • Escape characters: If you want to use literal characters that look like directives, escape them with a preceding % or just include them as normal text. For example, to include a literal %, use %%.
  • Leading zeros: Most directives produce zero-padded numbers, but you can remove padding by formatting integers yourself or using %-d (on Unix-like systems) to omit leading zeros.
  • Locale awareness: Some directives like %B and %A output names based on your system locale, so outputs may vary by user.
  • Always test your formats: Because date formatting strings are sensitive, small mistakes can cause errors or unexpected output. Testing is key!

Summary

Formatting dates in Python revolves primarily around the strftime() method of datetime objects, which uses format directives to customize output. You’ve learned how to:

  • Create datetime objects.
  • Use common formatting directives to build readable date strings.
  • Format today's date dynamically.
  • Handle time zones in formatting.
  • Parse date strings back into datetime objects with strptime().

Mastering these techniques will enable you to present dates exactly how your application or users need them.

Architecture of Formatting Dates
Architecture of Formatting Dates

💡 Pro Tip

Keep a cheat sheet of common strftime directives handy while coding. It speeds up your workflow and reduces errors.