Format a Date in Python
Turn a datetime into a string with strftime and parse strings back with strptime.
Also known as: strftime Python, Python datetime formatting
beginner
datetime.strftime(format) formats a datetime using directive codes like %Y-%m-%d. datetime.strptime(text, format) parses a string back into a datetime.
What it is
Python's datetime formats and parses with directive codes: %Y four-digit year, %m month, %d day, %H:%M:%S time. dt.strftime(...) produces a string; datetime.strptime(text, fmt) reads one back. For machine interchange, dt.isoformat() emits a standard ISO 8601 string in one call.
Be deliberate about time zones: datetime.now() returns a naive local time, while datetime.now(timezone.utc) returns an aware UTC value. Store and transmit aware UTC datetimes to avoid ambiguity.
Worked example
from datetime import datetime, timezone
now = datetime(2026, 7, 2, 15, 14, 0)
print(now.strftime("%Y-%m-%d %H:%M")) # 2026-07-02 15:14
# Parse a string back into a datetime
parsed = datetime.strptime("2026-07-02", "%Y-%m-%d")
print(parsed.date()) # 2026-07-02
# ISO 8601 with UTC
print(datetime.now(timezone.utc).isoformat())
Failure mode — when it misleads
strptime raises ValueError if the string doesn't match the format exactly, including separators, so validate untrusted input. Mixing naive and aware datetimes (e.g. subtracting one from the other) raises TypeError; keep everything aware and in UTC internally to avoid subtle off-by-hours bugs around daylight saving.