Sub topic 11
Adding, subtracting, and comparing dates
This chapter assumes you can create date and datetime objects and know that timedelta represents a duration, as covered in the previous chapter. You should also be comfortable with functions, try/except, and sorting lists. Here you will learn which arithmetic operations are allowed on dates, what they return, and where the common mistakes are.
The type rules
Date arithmetic follows a small set of rules. A difference between two points in time is a timedelta. A point in time moved by a timedelta is another point in time. Adding two points in time makes no sense, so Python rejects it.
| Expression | Result type |
|---|---|
| `date - date` | `timedelta` |
| `datetime - datetime` | `timedelta` |
| `date + timedelta` or `date - timedelta` | `date` |
| `datetime + timedelta` or `datetime - timedelta` | `datetime` |
| `timedelta + timedelta` | `timedelta` |
| `timedelta * int` or `timedelta / int` | `timedelta` |
| `timedelta / timedelta` | `float` |
| `date + date` | `TypeError` |
Inside a timedelta
A timedelta stores only three numbers: days, seconds, and microseconds. The constructor accepts weeks, days, hours, minutes, seconds, milliseconds, and microseconds, and normalizes them. The seconds attribute is always between 0 and 86399, and only days can be negative.
from datetime import timedelta
td = timedelta(days=1, hours=36, minutes=90)
print(td) # 2 days, 13:30:00
print(td.days) # 2
print(td.seconds) # 48600
print(td.total_seconds()) # 221400.0
neg = timedelta(hours=-1)
print(neg) # -1 day, 23:00:00
print(neg.days) # -1
print(neg.seconds) # 82800
print(neg.total_seconds()) # -3600.0The attribute seconds is not the total length in seconds. It is only the leftover part after whole days are removed. For the full duration, call total_seconds(). Reading td.seconds for a duration longer than a day is a classic bug. It is also wrong for negative durations, as the -1 day, 23:00:00 example shows.
Adding and subtracting with dates
Subtracting two dates gives a timedelta whose days attribute is the number of days between them. Adding a timedelta to a date gives a new date. The original objects are immutable, so nothing changes in place.
from datetime import date, timedelta
today = date(2026, 11, 26)
deadline = date(2026, 12, 25)
gap = deadline - today
print(gap) # 29 days, 0:00:00
print(gap.days) # 29
print(today + timedelta(weeks=2)) # 2026-12-10
print(today - timedelta(days=26)) # 2026-10-31
print(today + timedelta(hours=23)) # 2026-11-26The last line surprises many people. A date has no time of day, so date + timedelta uses only the days part and ignores seconds and microseconds. Adding 23 hours to a date changes nothing. If you need hours, use a datetime.
Differences between datetimes
For datetime objects the time of day counts, so days and seconds both carry information.
from datetime import datetime
start = datetime(2026, 11, 26, 9, 0)
end = datetime(2026, 11, 27, 17, 30)
diff = end - start
print(diff) # 1 day, 8:30:00
print(diff.days) # 1
print(diff.seconds) # 30600
print(diff.total_seconds() / 3600) # 32.5To express a duration in a unit, divide by a timedelta of that unit. This avoids hand-written constants.
from datetime import timedelta
span = timedelta(days=10)
print(span / timedelta(days=4)) # 2.5
print(span // timedelta(days=4)) # 2
print(span % timedelta(days=4)) # 2 days, 0:00:00
print(span / 2) # 5 days, 0:00:00
print(span * 3) # 30 days, 0:00:00
print(abs(timedelta(days=-3))) # 3 days, 0:00:00// counts how many whole periods fit, and % gives the remainder as a timedelta. Together they work well for splitting a duration into chunks.
There is no month or year in a timedelta
timedelta has no months or years argument, because months have different lengths and a year may have 365 or 366 days. Adding timedelta(days=365) to a date will not always land on the same calendar date next year.
To move by calendar months you must write the rule yourself. The decision you have to make is what happens when the target month is shorter than the starting day. Calling replace(month=2) on January 31 fails, because February 31 does not exist. A common rule is to clamp to the last day of the target month, which the function below does using calendar.monthrange.
import calendar
from datetime import date
def add_months(d, months):
index = d.year * 12 + (d.month - 1) + months
year, month = divmod(index, 12)
month += 1
last_day = calendar.monthrange(year, month)[1]
return d.replace(year=year, month=month, day=min(d.day, last_day))
print(add_months(date(2026, 1, 31), 1)) # 2026-02-28
print(add_months(date(2026, 11, 26), 3)) # 2027-02-26
print(add_months(date(2026, 11, 26), -12)) # 2025-11-26
try:
date(2026, 1, 31).replace(month=2)
except ValueError as exc:
print("ValueError:", exc) # ValueError: day is out of range for monthConverting the year and month into a single month index makes the arithmetic work in both directions and across year boundaries. The divmod call then splits the index back into a year and a zero-based month.
The same year-and-month rule applies to leap days. date(2024, 2, 29).replace(year=2025) raises ValueError, so any "same date next year" helper needs the same clamping.
Comparing dates
Dates, datetimes, and timedeltas all support ==, !=, <, <=, >, and >=. Because of that, sorted, min, and max work on them directly, and you can chain comparisons to test a range.
from datetime import date, datetime
dates = [date(2026, 12, 25), date(2026, 3, 1), date(2026, 11, 26)]
print([d.isoformat() for d in sorted(dates)])
# ['2026-03-01', '2026-11-26', '2026-12-25']
print(min(dates), max(dates)) # 2026-03-01 2026-12-25
window_start = date(2026, 11, 1)
window_end = date(2026, 11, 30)
print(window_start <= date(2026, 11, 26) <= window_end) # True
print(date(2026, 1, 1) == datetime(2026, 1, 1)) # False
try:
date(2026, 1, 1) < datetime(2026, 1, 1)
except TypeError:
print("TypeError") # TypeErrordatetime is a subclass of date, which causes a trap. A plain date and a datetime are never equal, even at midnight, and ordering them raises TypeError. Convert one side first, for example with dt.date() or datetime.combine(d, time.min).
Gotchas and edge cases
- Naive and aware values do not mix. Subtracting or ordering a naive
datetimeagainst an aware one raisesTypeError. Equality between them returnsFalsewithout an error. The next chapters cover time zones in detail. - Aware datetimes compare by the instant they represent. Noon UTC equals 21:00 in Tokyo on the same day, even though the clock readings differ.
- Daylight saving time is not applied to naive arithmetic. Adding
timedelta(days=1)moves the calendar date and keeps the clock reading. It does not add 24 real hours across a clock change. For absolute durations, convert to UTC first. - Range limits exist. Going past
date.max(year 9999) or beforedate.min(year 1) raisesOverflowError. - Weekday numbers.
weekday()returns Monday as 0 and Sunday as 6.isoweekday()returns Monday as 1 and Sunday as 7. For 2026-11-26,weekday()is 3, a Thursday.
Exercises
Exercise
How many days are there between date(2026, 11, 26) and date(2027, 1, 1), and which expression produces that number?
Show answer
There are 36 days. The expression is (date(2027, 1, 1) - date(2026, 11, 26)).days. Subtracting two dates gives a timedelta, and its days attribute holds the count.
Exercise
For td = timedelta(hours=-1), what are td.days and td.seconds, and why is td.seconds a poor way to get the duration?
Show answer
td.days is -1 and td.seconds is 82800. A timedelta normalizes so that seconds is always between 0 and 86399, which means -1 hour is stored as -1 day plus 23 hours. The correct total is td.total_seconds(), which returns -3600.0.
Exercise
What does add_months(date(2026, 1, 31), 1) return in this chapter's implementation, and what would date(2026, 1, 31).replace(month=2) do instead?
Show answer
add_months returns date(2026, 2, 28) because it clamps the day to the last day of February. replace(month=2) raises ValueError, because February 31 does not exist.