Python Glossary Русский

all Python 3datetimeterm

date arithmetic

date

Subtracting one date from another gives a timedelta. Adding a timedelta gives a new date.

Syntax

d1 - d2
d + timedelta(days=n)

timedelta has no months or years — only days, seconds and microseconds — so "add one month" simply cannot be written this way; compute it with calendar.monthrange() and replace(), or reach for a third-party library. A date accepts only a timedelta, never a plain number: date + 1 raises TypeError. The difference between two dates is always a whole number of days in diff.days, with none of the timezone or DST surprises that datetime arithmetic can bring.

Examples

from datetime import date, timedelta
d1 = date(2024, 12, 31)
d2 = date(2024, 1, 1)
diff = d1 - d2
print(diff.days)  # → 365
d3 = date.today() + timedelta(days=7)
print(d3)  # → через неделю
print(date(2024,3,1) > date(2024,1,1))  # → True
print(date.fromisoformat('2024-12-25') - date.today())

See also

Open in the full glossarydocs.python.orgReport an inaccuracy