← Learning Hub
Intermediate

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
You can edit this code.

Text to dates and back

strptime reads a date from text using a pattern; strftime writes one.

Example
You can edit this code.
  • %d day, %m month number, %b short month name, %Y year
  • %H hour (24h), %I hour (12h), %M minutes, %p AM/PM
  • %A weekday name

Time zones

Example
You can edit this code.
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-")