Sub topic 2
Measuring and shifting time with timedelta
A timedelta is a length of time, such as "3 days" or "90 minutes". It is not a point on the calendar. You get one when you subtract two dates or datetimes, and you use one to move a date or datetime forward or backward. This chapter covers how timedelta stores its value, which operators accept it, and where it surprises people.
This chapter assumes you know the date, time, and datetime types from the previous chapter and can read basic Python 3.9 or later code. All examples here use naive values (no time zone attached). Time zones come in later chapters, and a callout below flags where they change the rules.
What a timedelta stores
Internally, a timedelta keeps exactly three integers, whatever units you passed in:
days, which can be negative and ranges from -999999999 to 999999999.seconds, always from 0 to 86399.microseconds, always from 0 to 999999.
The constructor accepts weeks, days, hours, minutes, seconds, milliseconds, and microseconds. All are keyword arguments, all default to 0, and all may be negative or fractional. Python adds them together and normalizes the result into the three stored fields.
from datetime import timedelta
d = timedelta(weeks=1, days=2, hours=3, minutes=30, seconds=15, milliseconds=500)
print(d)
print(repr(d))
print(d.days, d.seconds, d.microseconds)This prints:
9 days, 3:30:15.500000
datetime.timedelta(days=9, seconds=12615, microseconds=500000)
9 12615 500000The week became 7 days, the hours and minutes folded into 12615 seconds, and the 500 milliseconds became 500000 microseconds.
Negative values normalize in a way that surprises people. Only days carries the sign. The other two fields stay non-negative.
from datetime import timedelta
neg = timedelta(hours=-1)
print(neg.days, neg.seconds, neg.microseconds)
print(neg.total_seconds())
print(neg)
print(timedelta(days=1, hours=-25))This prints:
-1 82800 0
-3600.0
-1 day, 23:00:00
-1 day, 23:00:00"Minus one hour" is stored as "minus one day, plus 23 hours". That is arithmetically the same, but it is confusing if you read the fields directly.
Where timedeltas come from
You create a timedelta in two ways. You can call the constructor, or you can subtract two values of the same kind. Subtracting two date objects, or two datetime objects, returns a timedelta.
from datetime import date, datetime
today = date(2026, 11, 26)
launch = date(2026, 12, 25)
left = launch - today
print(left)
print(left.days)
start = datetime(2026, 11, 26, 9, 0)
end = datetime(2026, 11, 28, 17, 30, 30)
diff = end - start
print(diff)
print(diff.total_seconds())This prints:
29 days, 0:00:00
29
2 days, 8:30:30
203430.0The result is negative when the left side is earlier, so today - launch gives -29 days, 0:00:00. Use abs() when you only want the size of the gap.
Operators that accept a timedelta
The table lists the combinations that work. Anything not listed raises TypeError.
| Expression | Result type | Notes |
|---|---|---|
| `date - date` | `timedelta` | Whole days only. |
| `datetime - datetime` | `timedelta` | Both must be naive, or both aware. |
| `date + timedelta` | `date` | Uses only the `days` part. |
| `datetime + timedelta` | `datetime` | Uses all parts. |
| `datetime - timedelta` | `datetime` | Moves backward. |
| `timedelta + timedelta` | `timedelta` | Also works with `-`. |
| `timedelta * int` or `float` | `timedelta` | Scales the duration. |
| `timedelta / int` or `float` | `timedelta` | Rounds to the nearest microsecond. |
| `timedelta / timedelta` | `float` | How many times one fits in the other. |
| `timedelta // timedelta` | `int` | Whole number of times it fits. |
| `timedelta % timedelta` | `timedelta` | The remainder. |
A date ignores everything in a timedelta except whole days. This is easy to miss:
from datetime import date, timedelta
print(date(2026, 11, 26) + timedelta(days=1, hours=23))This prints 2026-11-27. The 23 hours are dropped silently, not rounded. If you need the time of day, use a datetime.
A time object does not support arithmetic with timedelta at all, because "11:07 plus 14 hours" has no answer without a day to roll into. Combine it with a date first using datetime.combine, then add.
Scaling and dividing durations
Multiplying and dividing are handy for averages, scheduling, and progress estimates.
from datetime import timedelta
print(timedelta(minutes=45) * 3)
print(timedelta(hours=1) / 4)
print(timedelta(hours=5) / timedelta(minutes=20))
print(timedelta(hours=5) // timedelta(minutes=45))
print(timedelta(hours=5) % timedelta(minutes=45))
print(divmod(timedelta(hours=5), timedelta(minutes=45)))This prints:
2:15:00
0:15:00
15.0
6
0:30:00
(6, datetime.timedelta(seconds=1800))The last three lines say that 45-minute blocks fit into 5 hours six times, with 30 minutes left over.
You can compare timedeltas with <, >, and ==. A zero timedelta is falsy. sum() needs an explicit start value, because its default start is the integer 0, which cannot be added to a timedelta:
from datetime import timedelta
durations = [
timedelta(minutes=12),
timedelta(minutes=47, seconds=30),
timedelta(hours=1, minutes=5),
]
total = sum(durations, timedelta())
print(total)
print(total / len(durations))
print(max(durations))
limit = timedelta(minutes=5)
print(bool(timedelta(0)), durations[0] > limit)This prints:
2:04:30
0:41:30
1:05:00
False TrueReading values back out
A timedelta has three read-only attributes (days, seconds, microseconds) and one method, total_seconds().
The most common error is to use .seconds as if it were the whole duration. It is only the leftover part below one day.
from datetime import timedelta
gap = timedelta(days=2, hours=8, minutes=30, seconds=30)
print(gap.seconds)
print(gap.total_seconds())This prints 30630 and 203430.0. The first value is 8 hours 30 minutes 30 seconds. The two days are missing. Use total_seconds() for the full length.
str(timedelta) is readable, but it has no hours-only form and it prints 1 day, 2:00:00 for 26 hours. If you need HH:MM:SS with hours above 23, write a small helper:
from datetime import timedelta
def format_hms(delta):
total = int(delta.total_seconds())
sign = "-" if total < 0 else ""
hours, rest = divmod(abs(total), 3600)
minutes, seconds = divmod(rest, 60)
return f"{sign}{hours:02}:{minutes:02}:{seconds:02}"
print(format_hms(timedelta(days=1, hours=2, minutes=3, seconds=4)))
print(format_hms(timedelta(minutes=-90)))This prints 26:03:04 and -01:30:00. Taking abs() before splitting avoids the negative-day normalization shown earlier.
No months or years
timedelta has no months or years argument. A month is 28 to 31 days and a year is 365 or 366, so neither is a fixed length of time. Adding timedelta(days=30) is not the same as adding one month:
from datetime import date, timedelta
print(date(2026, 1, 31) + timedelta(days=30))This prints 2026-03-02, which skips February entirely. For calendar months you must choose a rule for days that do not exist, such as clamping to the last day of the month. This helper uses that rule with the standard library:
import calendar
from datetime import date
def add_months(d, months):
index = d.month - 1 + months
year = d.year + index // 12
month = index % 12 + 1
day = min(d.day, calendar.monthrange(year, month)[1])
return date(year, month, day)
print(add_months(date(2026, 1, 31), 1))
print(add_months(date(2026, 11, 30), 3))
print(add_months(date(2026, 3, 31), -1))This prints 2026-02-28, 2027-02-28, and 2026-02-28. The third-party python-dateutil package offers relativedelta for the same job, with a similar clamping rule.
Limits and precision
The resolution is one microsecond. Float arguments are rounded to the nearest microsecond, so timedelta(seconds=0.0000004) is zero. total_seconds() returns a float, which can lose precision for very long durations. If you need an exact integer, divide by a unit:
from datetime import timedelta
delta = timedelta(days=3, microseconds=7)
print(delta // timedelta(microseconds=1))
print(delta / timedelta(seconds=1))This prints 259200000007 and 259200.000007. The first value is an exact integer count of microseconds.
Results outside the supported range raise OverflowError:
from datetime import date, timedelta
try:
date(9999, 12, 31) + timedelta(days=1)
except OverflowError as e:
print(type(e).__name__)This prints OverflowError. The same happens when a datetime moves before year 1.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Using `delta.seconds` for the total length | Drops whole days | Use `delta.total_seconds()` |
| Adding `timedelta(days=30)` for "one month" | Lands on the wrong day | Use a month helper or `relativedelta` |
| Adding hours to a `date` | Hours are ignored | Use a `datetime` |
| Adding a `timedelta` to a `time` | `TypeError` | Use `datetime.combine` first |
| Using `sum(deltas)` | `TypeError` from adding `int` and `timedelta` | Use `sum(deltas, timedelta())` |
| Printing a negative `timedelta` to users | Shows `-1 day, 23:00:00` | Format it with a helper that uses `abs()` |
| Mixing naive and aware datetimes in a subtraction | `TypeError` | Make both naive or both aware |
Exercise
A job started at datetime(2026, 11, 26, 22, 15) and finished at datetime(2026, 11, 28, 1, 45). Write the expression that gives the duration in whole minutes as an integer, and say why (end - start).seconds // 60 is wrong.
Show answer
Use (end - start) // timedelta(minutes=1), which gives 1650. The duration is 1 day, 3:30:00, which is 27.5 hours, or 1650 minutes. The .seconds attribute holds only the part below one day (12600 seconds), so .seconds // 60 gives 210 and drops the full day.
Exercise
What does date(2026, 11, 26) + timedelta(hours=47) return, and what would change if the left side were datetime(2026, 11, 26)?
Show answer
It returns date(2026, 11, 27). The date type uses only the days part of the timedelta, and 47 hours is 1 day plus 23 hours, so the 23 hours are discarded. With datetime(2026, 11, 26) the result is datetime(2026, 11, 27, 23, 0), because a datetime keeps the full duration.