Dates and Times
The datetime module handles dates, times and the gaps between them (timedelta).
Almost every app deals with dates: order dates, delivery estimates, due dates, subscriptions, reports for "last month". Date maths is full of traps - months have different lengths, there are leap years and time zones - so always use the datetime module instead of doing the arithmetic yourself.
Example
Text to dates and back
strptime reads a date from text using a pattern; strftime writes one.
Example
%dday,%mmonth number,%bshort month name,%Yyear%Hhour (24h),%Ihour (12h),%Mminutes,%pAM/PM%Aweekday name
Time zones
Example
Store times in UTC (or with a time zone) and convert only for display.
datetime.now() without a zone gives the computer's local time, which differs between computers.Key points
- date, datetime and timedelta handle dates and gaps.
- strptime reads text into dates; strftime formats dates as text.
- Use time zones (zoneinfo) for real systems; store in UTC.
📝 Test yourself
1. Which adds 7 days to a date d?
2. Which function turns the text "26/11/2026" into a date?
3. Fill in the format code for a 4-digit year:
d.strftime("%d-%m-")
