Python strftime() Method


When working with dates and times in Python, formatting and displaying them in a human-readable way is a common task. Python's strftime() method, which stands for "string format time", allows you to convert datetime objects into formatted strings. This method provides a flexible way to represent time and dates in various formats, making it easy to tailor the output for specific use cases like logging, reports, or user interfaces.

In this guide, we'll walk you through how to use strftime(), explain its syntax, and provide practical examples for formatting dates and times in Python.


Table of Contents

  1. Introduction to strftime()
  2. Commonly Used Format Codes
  3. Basic Examples of strftime()
  4. Advanced strftime() Formatting
  5. Formatting Date and Time for Different Cultures
  6. Practical Use Cases
  7. Best Practices and Tips

Introduction to strftime()

The strftime() method is used to format datetime objects into strings in Python. It’s a part of the datetime module, which is the go-to library for handling dates and times in Python. The method takes a string as an argument that specifies the desired output format using special format codes. These format codes are placeholders that represent different parts of a date or time.

Syntax of strftime()

datetime_object.strftime(format_string)
  • datetime_object: The datetime object you want to format.
  • format_string: A string containing format codes that define the output format.

Example: Using strftime() to Format the Current Date and Time

import datetime

# Get the current date and time
current_datetime = datetime.datetime.now()

# Format the datetime object
formatted_datetime = current_datetime.strftime("%Y-%m-%d %H:%M:%S")
print("Formatted DateTime:", formatted_datetime)

Output:

Formatted DateTime: 2024-11-24 14:30:45

Commonly Used Format Codes

The format string passed to strftime() can contain various placeholders that represent different components of the date and time. Here are some of the most commonly used format codes:

Format Code Description Example
%Y Year with century (e.g., 2024) 2024
%m Month as a zero-padded decimal number (01-12) 11
%d Day of the month as a zero-padded decimal number (01-31) 24
%H Hour (24-hour clock) as a zero-padded decimal number (00-23) 14
%M Minute as a zero-padded decimal number (00-59) 30
%S Second as a zero-padded decimal number (00-59) 45
%A Full weekday name (e.g., Monday) Sunday
%B Full month name (e.g., January) November
%p AM/PM indicator (e.g., AM or PM) PM
%I Hour (12-hour clock) as a zero-padded decimal number (01-12) 02
%j Day of the year as a zero-padded decimal number (001-366) 329
%w Weekday as a decimal number (0-6, where Sunday is 0) 6

Basic Examples of strftime()

Let’s look at some basic examples of using strftime() to format the current date and time.

Example 1: Formatting a Full Date

import datetime

# Get the current date
current_date = datetime.datetime.now()

# Format the date as "Year-Month-Day"
formatted_date = current_date.strftime("%Y-%m-%d")
print("Formatted Date:", formatted_date)

Output:

Formatted Date: 2024-11-24

Example 2: Formatting Date and Time

import datetime

# Get the current date and time
current_datetime = datetime.datetime.now()

# Format as "Day, Month Name Year, Hour:Minute:Second"
formatted_datetime = current_datetime.strftime("%A, %B %d, %Y %H:%M:%S")
print("Formatted DateTime:", formatted_datetime)

Output:

Formatted DateTime: Sunday, November 24, 2024 14:30:45

Example 3: Formatting with AM/PM

import datetime

# Get the current datetime
current_datetime = datetime.datetime.now()

# Format with AM/PM
formatted_time = current_datetime.strftime("%I:%M %p")
print("Formatted Time with AM/PM:", formatted_time)

Output:

Formatted Time with AM/PM: 02:30 PM

Advanced strftime() Formatting

You can combine various format codes to create custom formats, which is useful when you need to display the date and time in specific formats (e.g., logs, reports, or dashboards).

Example 1: Creating a Custom Format

import datetime

# Get the current date and time
current_datetime = datetime.datetime.now()

# Custom format "Day of the week, Month Day, Year"
custom_format = current_datetime.strftime("%A, %B %d, %Y")
print("Custom Formatted Date:", custom_format)

Output:

Custom Formatted Date: Sunday, November 24, 2024

Example 2: Using Ordinal Date Format (Day of Year)

import datetime

# Get the current date
current_date = datetime.datetime.now()

# Format as "Day X of the Year"
ordinal_format = current_date.strftime("Day %j of the Year")
print("Ordinal Formatted Date:", ordinal_format)

Output:

Ordinal Formatted Date: Day 329 of the Year

Formatting Date and Time for Different Cultures

Python’s strftime() method is also flexible enough to format dates according to local conventions. While strftime() itself does not handle locale-aware formatting directly, you can set the locale of your system using the locale module to change how months and weekdays are displayed.

Example: Setting Locale for Date Formatting

import datetime
import locale

# Set locale to French
locale.setlocale(locale.LC_TIME, 'fr_FR.UTF-8')

# Get the current date
current_date = datetime.datetime.now()

# Format in French
formatted_date = current_date.strftime("%A, %B %d, %Y")
print("Formatted Date in French:", formatted_date)

Output:

Formatted Date in French: dimanche, novembre 24, 2024

Note: Locale settings depend on the system's available locales. You may need to install language-specific locale files for this to work.


Practical Use Cases

1. Logging with Timestamps

A common use case for strftime() is adding timestamps to logs. You can generate a timestamp in the desired format to include in log entries.

import datetime

# Get the current datetime
current_datetime = datetime.datetime.now()

# Format the datetime for logging
log_timestamp = current_datetime.strftime("%Y-%m-%d %H:%M:%S")
print(f"[{log_timestamp}] - Log message")

Output:

[2024-11-24 14:30:45] - Log message

2. File Naming with Dates

If you need to generate unique file names based on the current date and time, strftime() can be used to format the name.

import datetime

# Get the current datetime
current_datetime = datetime.datetime.now()

# Format as part of a filename
filename = current_datetime.strftime("report_%Y%m%d_%H%M%S.txt")
print("Generated File Name:", filename)

Output:

Generated File Name: report_20241124_143045.txt

Best Practices and Tips

  1. Use Raw Strings: When writing format codes, always use raw strings (i.e., prefix your format strings with r) to avoid issues with escape sequences like \n and \t.

    formatted_date = current_datetime.strftime(r"%Y-%m-%d %H:%M:%S")
    
  2. Be Mindful of Locales: If your application needs to support multiple languages or formats, consider using the locale module to handle different formats based on user preferences.

  3. Use strftime() for Readable Formats: If you're outputting dates and times for users, strftime() offers an easy way to create human-readable formats. For machine-readable formats, consider using ISO 8601 (%Y-%m-%dT%H:%M:%S).

  4. Time Zone Handling: To include time zone information, use time zone-aware datetime objects with %Z for the time zone name and %z for the UTC offset.