Free lab Real Python 3. Zero installs. Your code stays in this browser. Open the playground

Dates & Times

14 min 30 XP
Study loop Read Predict Run Tweak Prove Review
Lesson 2 of 5 · View course roadmap
Step 1

Learn the idea

Date math trips up every language — Python's datetime module makes it sane:

  • date(2026, 7, 19) — construct; date.today() — now
  • timedelta(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.

Step 2

Try it yourself

Blank · autosaved

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”.

PYexample.py
+ Enter to run
Output appears here…
Step 3

Pass the challenge +30 XP

Blank · autosaved

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.

Target output
199
2026-10-27
PYchallenge.py
Run your code to check it…
Step 4

Check your understanding

1. What type does date2 - date1 return?
2. strptime is for…
Last step

Your notes (saved on this device)

Tip: use and to move between lessons, K to search everything.

Your next ten minutes

Write Python that does something useful.

Start free. No install, no card, no passive video marathon.

Start learning free → Explore the path