Dates and times · 2 / 15 Theory

Date arithmetic with timedelta

Adding 30 days to a date seems easy until you have to think about months of 28, 30 and 31 days and leap years. timedelta does all the work.

What a timedelta is

A timedelta represents a duration: an amount of time, not a specific moment. It is created by giving days, seconds, hours, minutes or weeks.

from datetime import timedelta

d = timedelta(days=2, hours=3, minutes=30)
print(d)                  # 2 days, 3:30:00
print(d.days)             # 2
print(d.seconds)          # 12600   (only the hours/min/sec part: 3 h 30 min)
print(d.total_seconds())  # 185400.0 (EVERYTHING in seconds)
print(timedelta(weeks=1) == timedelta(days=7))   # True

Careful: .seconds is only the part left over from the days, not the total. For the total always use total_seconds().

Adding and subtracting days

from datetime import date, timedelta

f = date(2026, 1, 31)
print(f + timedelta(days=30))   # 2026-03-02
print(f - timedelta(days=31))   # 2025-12-31
print(date(2024, 2, 28) + timedelta(days=1))   # 2024-02-29  (leap year)
print(date(2026, 2, 28) + timedelta(days=1))   # 2026-03-01

Practise with Add days to a date.

Subtracting two dates

Subtracting two dates gives a timedelta with the difference in days (negative if the first one is earlier than the second).

from datetime import date

a = date(2026, 3, 1)
b = date(2026, 3, 20)
print(b - a)          # 19 days, 0:00:00
print((b - a).days)   # 19
print((a - b).days)   # -19

You apply it in Days between two dates.

Durations with hours and minutes

With datetime the subtraction includes the hours. To show the duration in days, hours and minutes you use divmod with total_seconds().

from datetime import datetime

start = datetime(2026, 3, 15, 9, 30)
end = datetime(2026, 3, 16, 11, 45)
duration = end - start
print(duration)   # 1 day, 2:15:00

seconds = int(duration.total_seconds())
days, remainder = divmod(seconds, 86400)
hours, remainder = divmod(remainder, 3600)
minutes = remainder // 60
print(days, hours, minutes)   # 1 2 15

It is the computation of Duration between two moments.

Going through a range of dates

A loop that adds one day on each turn goes through all the dates between two dates. This is how, for example, working days are counted.

from datetime import date, timedelta

day = date(2026, 11, 9)          # Monday
last = date(2026, 11, 15)        # Sunday
working = 0
while day <= last:
    if day.weekday() < 5:        # Monday to Friday
        working += 1
    day += timedelta(days=1)
print(working)   # 5

You practise it in Working days.

What timedelta does not do: add months

timedelta has no months or years, because they do not always last the same. For "the same day of next month" you have to compute it by hand or use calendar.monthrange (next article).

from datetime import date

f = date(2026, 1, 31)
next_month = f.replace(month=2) if False else None   # date(2026, 2, 31) does not exist
print(next_month)   # None