date, timedelta & weekdays

Dates and times

Lesson 16 of 20 · 11 min · Module 5: Real-world data

Deadlines, subscriptions, and reports all depend on dates. The datetime module does calendar arithmetic correctly, including month lengths and leap years.

Start this lesson →

Free. No installation: you write and run the code in your browser, and it is checked automatically.

By the end, you’ll be able to…

  • Parse and format ISO dates
  • Calculate with timedelta
  • Use weekday() for calendar rules

The idea

date.fromisoformat("2026-10-20") parses an ISO date. Subtracting two dates gives a timedelta, whose .days is the difference. Adding timedelta(days=1) moves forward one day. d.weekday() is 0 for Monday through 6 for Sunday.

from datetime import date, timedelta
start = date.fromisoformat("2026-02-27")
print(start + timedelta(days=2))
print(start.weekday())

01ISO dates are the safe format

2026-10-20 is unambiguous everywhere, sorts correctly as text, and is what date.fromisoformat and .isoformat() use. 10/11/2026 means different days in the US and Europe.

02Let timedelta do the calendar

date(2028, 2, 28) + timedelta(days=1) is February 29 because 2028 is a leap year. Doing date arithmetic by hand with day and month numbers is a classic source of bugs.

from datetime import date, timedelta
print(date(2026, 12, 31) + timedelta(days=1))
Output
2027-01-01

03Weekdays are numbers

weekday() returns 0 for Monday and 6 for Sunday, so weekday() < 5 means a working day. isoweekday() is the same with Monday as 1.

Your turn

Write days_until(target, today): both are ISO date strings; return the number of days from today to target (negative if target is in the past). Write add_business_days(start, n): return the ISO date that is n working days (Monday to Friday) after start, for n ≥ 0. Weekend days are skipped.

What the checks look for

  • Counts days until a date
  • Returns negative numbers for past dates and handles leap years
  • Skips weekends
  • Adding zero business days keeps the date
Try it in the editor →

Take this with you

Parse, calculate with timedelta, format back to ISO.

Go a little further

Accept a set of public holidays and skip those days too.

Learn Python Intermediate for free

20 short lessons with real code and instant checks.

See the whole course →