PythiloLesson 28 of 30 · progress kept in this browser

Dates and times

The datetime module has date for calendar days, datetime for a day plus a time of day, and timedelta for a length of time.

from datetime import date, timedelta

d = date.fromisoformat("2024-02-27")
later = d + timedelta(days=3)
print(later)               # 2024-03-01
print((later - d).days)    # 3
print(later.strftime("%d %b %Y"))
print(later.weekday())     # 4, a Friday
print(later.isoformat() > "2024-01-31")
  • fromisoformat reads, and isoformat writes, the YYYY-MM-DD form. Text in that form also sorts in date order.
  • Adding a timedelta handles month ends and leap years for you. Subtracting two dates gives a timedelta, and .days is a whole number.
  • strftime formats a date with codes such as %Y, %m, %d and %A, the weekday name. strptime parses text with the same codes.
  • weekday() counts Monday as 0.

date.today() and datetime.now() change every day. Pass dates into your functions instead of reading the clock inside them, so the functions stay testable.

Your task

Write days_between(start, end) taking two YYYY-MM-DD strings and returning the number of days from start to end, negative if end is earlier. Write due_date(start, days) returning the date days after start, as a YYYY-MM-DD string.