Sub topic 11
Adding, Subtracting, and Comparing Dates
This chapter assumes you can create date and datetime objects and know what a timedelta is, as covered in the previous chapter. It also assumes you are comfortable with basic Python operators.
Which operations are allowed
Date arithmetic follows a few type rules. A timedelta is a length of time. A date is a point in time. Adding two points in time makes no sense, so Python rejects it.
| Expression | Result type |
|---|---|
| `date + timedelta` | `date` |
| `date - timedelta` | `date` |
| `date - date` | `timedelta` |
| `timedelta + timedelta` | `timedelta` |
| `timedelta * int` | `timedelta` |
| `timedelta / timedelta` | `float` |
| `date + date` | `TypeError` |
The same rules apply to datetime.
Shifting a date and measuring a gap
from datetime import date, timedelta
today = date(2026, 11, 26)
deadline = date(2027, 1, 1)
print(today + timedelta(days=30)) # 2026-12-26
print(today - timedelta(weeks=2)) # 2026-11-12
left = deadline - today
print(left) # 36 days, 0:00:00
print(left.days) # 36
print(left // timedelta(weeks=1)) # 5 whole weekstimedelta accepts days, seconds, microseconds, milliseconds, minutes, hours, and weeks. It has no months or years, because their lengths vary. Passing months=1 raises TypeError. If you need "one month later", use replace and handle the edge cases yourself:
from datetime import date
d = date(2026, 1, 31)
try:
print(d.replace(month=2))
except ValueError as exc:
print("No such date:", exc) # day is out of range for monthHow timedelta stores its value
A timedelta keeps only three fields: days, seconds, and microseconds. Python normalizes every input into those fields, and only days can be negative. This surprises people when they work with negative durations.
from datetime import timedelta
gap = timedelta(hours=-1)
print(gap.days, gap.seconds) # -1 82800
print(gap.total_seconds()) # -3600.0
long_gap = timedelta(hours=36)
print(long_gap.days) # 1
print(long_gap.seconds) # 43200The .seconds attribute is not the total duration. It is only the leftover seconds after whole days are removed. For the full length of a duration, use total_seconds().
Comparing dates
Dates and datetimes compare with <, <=, ==, !=, >, and >=. Earlier points in time are smaller. Because they are ordered, min, max, and sorted work on them directly.
from datetime import date, datetime
a = date(2026, 11, 26)
b = date(2027, 1, 1)
print(a < b) # True
print(max(a, b)) # 2027-01-01
print(sorted([b, a])[0]) # 2026-11-26
start = datetime(2026, 11, 26, 9, 0)
end = datetime(2026, 11, 26, 17, 30)
print(end - start) # 8:30:00
print((end - start) > timedelta(hours=8)) # TrueThe last line needs timedelta imported. Add it to the first import line before you run the block: from datetime import date, datetime, timedelta.
Common errors
- Mixing
dateanddatetimein ordering. Adatetimeis a subclass ofdate, butdate(2026, 1, 1) < datetime(2026, 1, 1)raisesTypeError. Equality does not raise. It quietly returnsFalse. Convert one side first, for example withdt.date(). - Mixing naive and aware datetimes. Subtracting or ordering one with a time zone and one without raises
TypeError. A later chapter covers this. - Reading
.secondsas the whole duration. Usetotal_seconds()instead. - Expecting month arithmetic from
timedelta. There is none.
Exercise
Given start = datetime(2026, 11, 26, 22, 0) and end = datetime(2026, 11, 27, 6, 30), what are (end - start).days, (end - start).seconds, and (end - start).total_seconds()?
Show answer
The gap is 8 hours 30 minutes, which is less than a day. So .days is 0, .seconds is 30600, and total_seconds() is 30600.0.
Exercise
What happens when you evaluate date(2026, 11, 26) + date(2026, 12, 1)? What would you write to get the number of days between them?
Show answer
It raises TypeError, because adding two points in time is not defined. Subtract them instead: (date(2026, 12, 1) - date(2026, 11, 26)).days gives 5.