Deadlines, expiry times, ages and elapsed time are all date arithmetic.
A timedelta is a duration. Create one with keyword arguments: timedelta(days=7), timedelta(hours=1, minutes=30), timedelta(milliseconds=250).
Arithmetic:
datetime + timedeltaanddate + timedeltagive a later moment or day.datetime - datetimegives a timedelta.- Timedeltas add, subtract, multiply by numbers and divide:
td / timedelta(hours=1)gives hours as a float, andtd // timedelta(days=1)whole days.
Internally a timedelta is normalised to days, seconds (0 to 86399) and microseconds. Don't use .seconds to mean the total: for 1 day and 2 hours, .seconds is 7200. Use `td.total_seconds()`. Negative durations are normalised oddly too: timedelta(hours=-1) prints as -1 day, 23:00:00.
Adding to a date only uses whole days (the seconds part is ignored).
timedelta has no concept of months or years, because they have variable lengths. "One month after January 31" is a business rule; see the calendar-math lesson.
For measuring how long code takes, don't subtract datetime.now() values; the wall clock can jump. Use time.perf_counter() or time.monotonic().
Example
from datetime import date, datetime, timedelta
start = datetime(2025, 3, 1, 22, 0)
print(start + timedelta(hours=5)) # 2025-03-02 03:00:00
print(date(2025, 3, 1) - timedelta(weeks=1)) # 2025-02-22
td = datetime(2025, 3, 2, 2, 0) - datetime(2025, 3, 1, 0, 0)
print(td) # 1 day, 2:00:00
print(td.seconds) # 7200 (not the total!)
print(td.total_seconds()) # 93600.0
print(td / timedelta(hours=1)) # 26.0
print(td // timedelta(days=1)) # 1
print(timedelta(hours=-1)) # -1 day, 23:00:00
deadline = date(2025, 3, 31)
print((deadline - date(2025, 3, 1)).days) # 30Remember
timedeltais a duration; datetime minus datetime gives one- Use
total_seconds()or divide by a timedelta, never.secondsfor totals - timedelta has no months or years
Watch out for
- Reading
td.secondsas the total duration; it drops the days component.