Python strftime and strptime Format Codes
Complete reference for Python's strftime and strptime format codes. Learn percent-directive syntax for formatting and parsing dates with the datetime module.
Detailed Explanation
Python strftime / strptime Format Codes
Python's datetime module uses percent-prefixed directives for both formatting (strftime) and parsing (strptime). This syntax originated from the C standard library and is also used by Ruby and other languages.
Core Directives
| Directive | Meaning | Example |
|---|---|---|
%Y |
Year (4-digit) | 2026 |
%y |
Year (2-digit) | 26 |
%m |
Month (zero-padded) | 02 |
%-m |
Month (no padding) | 2 |
%B |
Full month name | February |
%b |
Abbreviated month | Feb |
%d |
Day (zero-padded) | 28 |
%-d |
Day (no padding) | 28 |
%A |
Full weekday | Saturday |
%a |
Abbreviated weekday | Sat |
%H |
Hour 24h (zero-padded) | 14 |
%I |
Hour 12h (zero-padded) | 02 |
%M |
Minute (zero-padded) | 30 |
%S |
Second (zero-padded) | 00 |
%p |
AM/PM | PM |
%j |
Day of year (zero-padded) | 059 |
%z |
UTC offset | +0900 |
%Z |
Timezone name | JST |
Formatting vs Parsing
from datetime import datetime
# Formatting (datetime → string)
dt = datetime(2026, 2, 28, 14, 30, 0)
dt.strftime("%Y-%m-%d %H:%M:%S") # "2026-02-28 14:30:00"
# Parsing (string → datetime)
datetime.strptime("2026-02-28 14:30:00", "%Y-%m-%d %H:%M:%S")
Platform-Specific Directives
The %- prefix (e.g., %-d, %-m) removes zero-padding on Linux/macOS but is not supported on Windows. On Windows, use %#d and %#m instead.
Common Patterns
"%Y-%m-%d" # 2026-02-28
"%Y-%m-%d %H:%M:%S" # 2026-02-28 14:30:00
"%B %d, %Y" # February 28, 2026
"%m/%d/%Y" # 02/28/2026
"%d/%m/%Y" # 28/02/2026
"%a, %d %b %Y %H:%M:%S %z" # Sat, 28 Feb 2026 14:30:00 +0900
"%I:%M %p" # 02:30 PM
Python 3.6+ f-strings
f"{dt:%Y-%m-%d %H:%M}" # "2026-02-28 14:30"
Use Case
Python strftime patterns are essential for logging configuration, Django/Flask template date rendering, data science report generation with pandas, CSV/Excel date column formatting, cron job output, and parsing dates from external APIs or file names.