Comparing and calculating with dates
Datetimes can be compared and subtracted, and time can be added to them. The datetime type takes care of the calendar: month lengths, leap years, the turn of the year.
Comparing
The comparison operators work on datetimes. An earlier moment is smaller than a later one:
from datetime import datetime
deadline = datetime(2026, 12, 14, 9, 0)
submitted = datetime(2026, 12, 14, 8, 45)
if submitted <= deadline:
print("Submitted in time")
else:
print("Too late")
Submitted in timeThe difference: timedelta
Subtracting one datetime from another gives a timedelta: a length of time, rather than a moment. Its attribute days holds the whole days, and seconds holds the rest, less than a day, in seconds:
from datetime import datetime
start = datetime(2026, 9, 1)
end = datetime(2026, 12, 18, 12, 0)
difference = end - start
print(difference)
print(difference.days)
print(difference.seconds)
108 days, 12:00:00
108
43200A timedelta has no attribute for hours, and none for months or years either, because months and years don't all have the same length:
from datetime import datetime
difference = datetime(2026, 3, 1, 18, 0) - datetime(2026, 3, 1, 9, 0)
print(difference.hours)
Traceback (most recent call last):
File "main.py", line 4, in <module>
print(difference.hours)
^^^^^^^^^^^^^^^^
AttributeError: 'datetime.timedelta' object has no attribute 'hours'Calculate hours from the seconds yourself: difference.seconds // 3600 is 9 here.
Adding time
To move a moment forward or back, add or subtract a timedelta. You make one with timedelta(...), giving the units you want as keyword arguments, like end= in print: days, weeks, hours, minutes. Import timedelta from the module too:
from datetime import datetime, timedelta
order = datetime(2026, 11, 27, 16, 0)
print("Delivery:", order + timedelta(days=3))
print("Return by:", order + timedelta(weeks=4))
print("Reminder:", order - timedelta(hours=20))
Delivery: 2026-11-30 16:00:00
Return by: 2026-12-25 16:00:00
Reminder: 2026-11-26 20:00:00Adding a plain number, as in order + 3, is a TypeError: Python can't know whether you mean days, hours or seconds.