How to Convert Date/Time to String in Python Using strftime()

The strftime() method, short for “string format time”, is a part of Python’s datetime module. It converts datetime objects (which represent dates and times) into customized, formatted strings. This is achieved through the use of special format codes that dictate the appearance of the output string.

strftime() offers the flexibility to present dates and times in the exact way that suits your application. Whether you need a simple month-day-year format, a detailed timestamp, or a format specific to a certain locale, strftime() can help you achieve this..

If you need to go the other way—converting formatted strings back into datetime objects—use the strptime() method (it uses the same format codes).

Let’s explore the strftime() method in detail, including its syntax, format codes, and practical examples.

Syntax

The syntax of the strftime() method is as follows:

datetime_object.strftime(format_string)

Where,

datetime_object: The datetime object you want to format.

format_string: A string composed of special format codes that dictate how the different components of the date and time will be represented.

Basic Examples

The strftime() method provides you loads of options for how exactly to represent your datetime object. For example, consider this format:

from datetime import datetime

current_time = datetime.now()

# Simple date format
print(current_time.strftime("%A,%d %B %Y"))
# Output: Friday,01 March 2024

In this example, the following format codes are used:

  • %A: Full weekday name
  • %d: Day of the month
  • %B: Full month name
  • %Y: Year with century (4 digits)

Format codes in strftime() always begin with a percentage sign %, which follows an old C standard. These codes resemble the old printf string formatting style, but they are not the same.

Let’s look at a few more examples:

# Current Date
print(current_time.strftime("%Y-%m-%d"))  # Output: 2024-03-01

# Current Time
print(current_time.strftime("%H:%M:%S"))  # Output: 14:35:00

# ISO 8601 Format 
print(current_time.strftime("%Y-%m-%dT%H:%M:%S"))  # Output: 2024-03-01T14:35:00

List of Format Codes

The format string can include various format codes. Each code acts as a placeholder that the strftime() method will replace with the corresponding value from the datetime object.

Below are tables of all format codes with explanations and examples. Note that the example outputs are based on the specific datetime of 2024-03-01 19:33:27 for demonstration purposes.

Format codes for Date

CodeExample Output
(2024-03-01 19:33:27)
Meaning
%aFriAbbreviated weekday name
%AFridayFull weekday name
%w5Weekday as a decimal number (0=Sunday, 6=Saturday)
%d01Day of the month as a zero-padded decimal number
%bMarAbbreviated month name
%BMarchFull month name
%m03Month as a zero-padded decimal number
%y24Year without century as a zero-padded decimal number
%Y2024Year with century as a decimal number

Format codes for Time

CodeExample Output
(2024-03-01 19:33:27)
Meaning
%H19Hour in 24-hour format (00-23)
%I07Hour in 12-hour format (01-12)
%pPMAM/PM
%M33Minute as a zero-padded decimal number
%S27Second as a zero-padded decimal number
%f148285Microsecond as a decimal number (000000-999999)
%z-0500 (if EST is your timezone)UTC offset in the form +/-HHMM[SS[.ffffff]]
%ZEST (if EST is your timezone)Time zone name

Format codes for Alternative Representations

CodeExample Output
(2024-03-01 19:33:27)
Meaning
%j061Day of the year as a zero-padded decimal number (001-366)
%U08Week number of the year (Sunday is first day of the week) 00-53
%W09Week number of the year (Monday is first day of the week) 00-53
%cFri Mar 1 19:33:27 2024Locale’s date and time representation
%x03/01/24Locale’s date representation
%X19:33:27Locale’s time representation

Format codes with Hyphen (Platform specific)

CodeExample Output
(2024-03-01 19:33:27)
Meaning
%-d1Day of the month (no leading zero)
%-m3Month as a decimal number (no leading zero)
%-H19Hour in 24-hour format (no leading zero)
%-I7Hour in 12-hour format (no leading zero)
%-M33Minute as a decimal number (no leading zero)
%-S27Second as a decimal number (no leading zero)
%-j61Day of the year (no leading zero)
%-U8Week number of the year (Sunday is first day of the week, no leading zero)
%-W9Week number of the year (Monday is first day of the week, no leading zero)

Plese note that format codes with hyphen work reliably on Unix-based systems (Linux, macOS). However, their behavior is inconsistent on Windows. Therefore, it’s highly recommended to test your code specifically on Windows environments if you plan to use them.

Formatting Time with AM/PM Notation

To format time with AM/PM notation, you’ll need two format codes:

  • %I: represents the hour in 12-hour format (e.g., 1, 2, …12).
  • %p: automatically displays “AM” or “PM” based on the time of day.

For example, to display the current time in 12-hour format with AM/PM, you would use the following format string:

from datetime import datetime

current_time = datetime.now()

formatted_time = current_time.strftime("%I:%M %p")
print(formatted_time)
# Output: 09:25 AM 

Handling Zero-padding

Some strftime() format codes allow for variations, like using a hyphen - to avoid zero-padding. For example, %m results in “03” for March, while %-m produces “3,” omitting the leading zero for the month of March.

from datetime import datetime

current_time = datetime.now()

# With Zero-padding
print(current_time.strftime("%Y.%m.%d"))    # Output: 2024.03.01

# Without Zero-padding
print(current_time.strftime("%Y.%-m.%-d"))  # Output: 2024.3.1

Note:

Format codes with hyphen work reliably on Unix-based systems (Linux, macOS). However, their behavior is inconsistent on Windows. Therefore, it’s highly recommended to test your code specifically on Windows environments if you plan to use them.

Additionally, it’s important to note that the hyphen only works with a limited set of format codes, primarily those related to days, months, and hours.

Adding Custom Text

The strftime() method replaces only those elements it identifies as format codes. As a result, any commas, spaces, or other characters you include directly within the format string will be printed as is.

This allows you to include regular text within the format string, making it easier to create more descriptive outputs. For example:

from datetime import datetime

current_time = datetime.now()

print(current_time.strftime("Today's date: %Y/%m/%d"))
# Output: Today's date: 2024/03/01

Using f-strings for Date Formatting

Python’s f-strings support the same format codes as strftime(). To use these codes within f-strings, you use colon : to separate your expression and the corresponding format code.

Here’s how you can use them:

from datetime import datetime

formatted_date = f"Today's date is {datetime.now():%B %d, %Y}"  
print(formatted_date)
# Output: Today's date is March 01, 2024

Formatting UNIX Timestamp into String

A UNIX timestamp is an integer representing the number of seconds elapsed since January 1st, 1970 at 00:00:00 UTC (often called the Unix epoch).

To format a UNIX timestamp into a string in Python, first convert the timestamp to a datetime object using fromtimestamp() method. Then, use the strftime() method to format the datetime object into your desired string representation.

from datetime import datetime

# Example timestamp
timestamp = 1677763200

# Convert the timestamp into a datetime object
dt_object = datetime.fromtimestamp(timestamp)

# Format using strftime()
formatted_string = dt_object.strftime("%Y-%m-%d %H:%M:%S")
print(formatted_string)
# Output: 2023-03-01 10:00:00

Handling Time Zones

If your datetime objects have time zone information attached, you can easily include those details in your formatted output. Let’s see how:

from datetime import datetime
from zoneinfo import ZoneInfo

# Specify the timezone
timezone = ZoneInfo('America/New_York')

# Get the current time in the specified timezone
current_time = datetime.now(timezone)

print(current_time.strftime("%Y-%m-%d %H:%M:%S %Z"))
# Output: 2024-03-01 20:15:45 EST 

In this example, the %Z code displays the time zone abbreviation (EST). For a more detailed offset, use the %z code:

print(current_time.strftime("%Y-%m-%d %H:%M:%S %z"))
# Output: 2024-03-01 23:15:00 -0500

Locale-specific Formatting

Locale-specific formatting involves displaying date and time information in a way that is understandable and familiar to users in a particular locale. For example, the month name might be “March” in the US locale but “März” in the German locale.

To achieve locale-specific formatting in Python, you use the locale module.

from datetime import datetime
import locale

now = datetime.now()

locale.setlocale(locale.LC_ALL, 'de_DE') # Set to German locale
print(now.strftime("%A, %d. %B %Y"))  
# Output: Freitag, 01. März 2024

Some More Practical Examples

Let’s look at some more practical examples of strftime().

Example 1: Logging with Timestamps

This example demonstrates how to generate timestamps in the format “YYYY-MM-DD_HH:MM:SS” and add them to your log messages for easier tracking and analysis.

from datetime import datetime
import logging

def log_event(message):
    timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
    logging.basicConfig(filename="log.txt", level=logging.INFO)
    logging.info(f"[{timestamp}] - {message}")

# Example usage
log_event("Application Started")
log_event("Database Connection Established") 
log_event("User Login Successful")

# Contents of the log.txt
# INFO:root:[2024-03-01_14-43-38] - Application Started
# INFO:root:[2024-03-01_14-43-38] - Database Connection Established
# INFO:root:[2024-03-01_14-43-38] - User Login Successful 

Example 2: File Naming with Dates

This example demonstrates how to embed the date into the filename itself, allowing for easy sorting and identification of reports created on different dates.

from datetime import datetime

def generate_report():
    report_date = datetime.now().strftime("%Y%m%d")
    report_name = f"sales_report_{report_date}.csv"
    # Code to generate and save the report in the CSV file 
    print("Successfully generated:",report_name)

generate_report() 

# Output: Successfully generated: sales_report_20240301.csv

Example 3: Conditional Date-Time Formatting

This example dynamically adjusts the formatting based on whether a task deadline has passed. It provides a user-friendly message indicating either when the deadline was missed or the number of days remaining until the deadline.

from datetime import datetime

task_deadline = datetime(2024, 3, 5, 16, 0)  

def format_deadline():
    now = datetime.now()
    if now > task_deadline:
        return now.strftime("Deadline passed on %b %d at %I:%M %p")
    else:
        days_left = (task_deadline - now).days
        return now.strftime(f"Deadline in {days_left} days (%B %d)")

print(format_deadline())
# Output: Deadline in 4 days (March 01)