Dates & Times
Lesson 2 of 5 · View course roadmap
Learn the idea
Date math trips up every language — Python's datetime module makes it sane:
date(2026, 7, 19)— construct;date.today()— nowtimedelta(days=30)— a duration you can add/subtract- Subtracting dates gives a timedelta:
(d2 - d1).days d.strftime("%d %B %Y")— format to string (format)datetime.strptime("2026-07-19", "%Y-%m-%d")— parse from string (parse)
Common codes: %Y year, %m month, %d day, %H:%M time, %A weekday name, %B month name.
Where you'll use this
Billing cycles, subscription expiry, 'posted 3 hours ago', report ranges, cron schedules — nearly every business rule has a date in it, and naive date math (day+1) breaks on month ends and leap years. timedelta doesn't.
Common mistakes
- Doing calendar math by hand — adding 1 to the day number fails on the 31st. Always use timedelta.
- Mixing up strftime (format → string) and strptime (parse ← string).
- Comparing dates as strings: as text, "2026-2-1" > "2026-10-1" — parse to date objects first.
- Ignoring timezones in anything user-facing — store UTC, convert at display time.
Pro tip
Log and store dates as ISO 8601 (YYYY-MM-DD) — it's unambiguous internationally and sorts correctly even as plain text. date.fromisoformat() parses it in one call.
Try it yourself
The lesson example is loaded and ready — press Run, then change something and run it again. Breaking it is part of learning. Want a clean slate? Tap “New blank”.
Output appears here…
Pass the challenge +30 XP
Compute how many days passed between 2026-01-01 and 2026-07-19, then print the date 100 days after 2026-07-19 in YYYY-MM-DD format.
199 2026-10-27
(d2 - d1).days, then d2 + timedelta(days=100) and strftime("%Y-%m-%d").
from datetime import date, timedelta
start = date(2026, 1, 1)
end = date(2026, 7, 19)
print((end - start).days)
print((end + timedelta(days=100)).strftime("%Y-%m-%d"))
Run your code to check it…
Check your understanding
Your notes (saved on this device)
Tip: use ← and → to move between lessons, ⌘K to search everything.