Formatting and Parsing
Use strftime and strptime.
Why format and parse?
Computers store dates as objects, but humans read them as text. Formatting turns a datetime into a string, and parsing turns a string back into a datetime.
strftime= string FROM time (format).strptime= string PARSE time (parse).
from datetime import datetime
now = datetime(2026, 5, 30, 14, 5)
print(now)Your first strftime
Call .strftime(format) on a datetime. Format codes start with %: %Y is a 4-digit year, %m is the month, and %d is the day.
from datetime import datetime
d = datetime(2026, 5, 30)
print(d.strftime('%Y-%m-%d'))All lessons in this course
- date, time, datetime
- Timedelta and Arithmetic
- Formatting and Parsing
- Time Zones with zoneinfo