Date Formatting & Parsing: strftime() & strptime()
When interacting with users, databases, or APIs, dates are passed back and forth as text strings (e.g., "08-Aug-2026" or "2026/08/08 14:30:00").
Python provides two essential methods for date conversion:
strftime()(String Format Time): Converts adatetimeobject into a readable text string.strptime()(String Parse Time): Converts a raw text string back into a Pythondatetimeobject.
Easy Mnemonic
finstrftimestands for Format (Output to String).pinstrptimestands for Parse (Input from String).
1. Converting Dates to Strings with strftime()
from datetime import datetime
now = datetime.now()
# Format 1: Standard YYYY-MM-DD
print(now.strftime("%Y-%m-%d")) # Output: 2026-08-08
# Format 2: Readable format (e.g. 08 August 2026)
print(now.strftime("%d %B %Y")) # Output: 08 August 2026
# Format 3: Time format (12-hour format with AM/PM)
print(now.strftime("%I:%M %p")) # Output: 01:45 PM
# Format 4: Complete timestamp with weekday
print(now.strftime("%A, %b %d, %Y - %H:%M:%S"))
# Output: Saturday, Aug 08, 2026 - 13:45:10
2. Essential Format Codes Cheatsheet
| Code | Meaning | Example Output |
|---|---|---|
%Y | 4-Digit Year | 2026 |
%y | 2-Digit Short Year | 26 |
%m | 2-Digit Month Number | 08 |
%B | Full Month Name | August |
%b | Short Month Name | Aug |
%d | Day of Month (01-31) | 08 |
%A | Full Weekday Name | Saturday |
%a | Short Weekday Name | Sat |
%H | 24-Hour Clock (00-23) | 14 |
%I | 12-Hour Clock (01-12) | 02 |
%M | Minutes (00-59) | 30 |
%S | Seconds (00-59) | 45 |
%p | AM / PM marker | PM |
3. Parsing Raw Text into Dates with strptime()
When receiving raw date strings from API JSON payloads or user input forms, use strptime() with the exact matching format template:
from datetime import datetime
raw_input_1 = "25/12/2026"
date_obj_1 = datetime.strptime(raw_input_1, "%d/%m/%Y")
print("Parsed Date:", date_obj_1.year) # Output: Parsed Date: 2026
raw_input_2 = "2026-Aug-15 09:30 AM"
date_obj_2 = datetime.strptime(raw_input_2, "%Y-%b-%d %I:%M %p")
print("Parsed Month:", date_obj_2.month) # Output: Parsed Month: 8
Quick Summary
strftime(format)(String From Time): Converts datetime objects into formatted custom text strings (e.g.,%Y-%m-%d).strptime(str, format)(String Parse Time): Parses raw strings from APIs or forms into Pythondatetimeobjects.- Core Format Codes:
%Y(4-digit year),%m(month number),%B(month name),%d(day),%H(24h) /%I(12h),%M(minute),%p(AM/PM).
What's Next?
Let's look at hardware timers, rate-limiting delays, and precision performance benchmarking with the time module!