Python strftime()
1. What is strftime()
strftime() converts a datetime object into a formatted string based on specified format codes.
from datetime import datetime
now = datetime.now()
formatted = now.strftime("%Y-%m-%d")
print(formatted) # e.g., 2025-11-24It is essential for displaying dates in human-readable formats, logs, and reports.
2. Basic Date Formatting
from datetime import datetime
now = datetime.now()
print(now.strftime("%d/%m/%Y")) # Day/Month/Year
print(now.strftime("%m-%d-%Y")) # Month-Day-YearCustomizes how date appears in different regional formats.
3. Time Formatting
from datetime import datetime
now = datetime.now()
print(now.strftime("%H:%M:%S")) # 24-hour format
print(now.strftime("%I:%M %p")) # 12-hour format with AM/PMUsed for clock displays and timestamping.
4. Including Day and Month Names
Enhances readability in user-facing outputs.
5. Combining Date and Time
Common format for logs and system monitoring.
6. Using strftime() for File Naming
Ideal for generating timestamped files safely.
7. ISO 8601 Format Using strftime
Used in APIs and structured data exchange.
8. Custom Human-Readable Format
Creates expressive, user-friendly messages.
9. Formatting Specific datetime Object
Formats fixed or scheduled execution dates.
10. Enterprise Use Case: Log Timestamp
Standard pattern for production logging and auditing systems.
Common strftime() Format Codes
strftime() Format Codes%Y
Full year
2025
%y
Short year
25
%m
Month (01-12)
11
%d
Day (01-31)
24
%H
Hour (24h)
19
%I
Hour (12h)
07
%M
Minute
45
%S
Second
59
%p
AM/PM
PM
%A
Weekday
Monday
%B
Month name
November
Summary
strftime() is a foundational tool for:
Formatting logs
Generating reports
File versioning
Time-based automation
User-interface display strings
It provides complete flexibility for representing date and time values.
Last updated