ZetCode

Python timedelta

last modified November 19, 2026 Python 3.15

In this article we work with the timedelta class from the datetime module. A timedelta is a duration: the difference between two dates or datetimes, or an amount of time we add to them.

The basics of dates and datetimes are covered in Python datetime.

A first timedelta

Subtracting one datetime from another gives a timedelta.

first_timedelta.py
from datetime import datetime

start = datetime(2026, 11, 19, 8, 45)
end = datetime(2026, 11, 19, 17, 15)

worked = end - start

print(worked)
print(type(worked))

The working day lasted eight and a half hours. The duration prints in the H:MM:SS form.

$ python first_timedelta.py
8:30:00
<class 'datetime.timedelta'>

Creating durations

The constructor takes the keyword arguments weeks, days, hours, minutes, seconds, milliseconds, and microseconds. They can be combined and they can be floats.

create_timedelta.py
from datetime import timedelta

print(timedelta(days=2))
print(timedelta(hours=36))
print(timedelta(minutes=90))
print(timedelta(weeks=1, days=1))
print(timedelta(milliseconds=1500))
print(timedelta(hours=1.5))

d = timedelta(weeks=1, hours=26, minutes=30, milliseconds=250)
print(d)
print(repr(d))
print(d.days, d.seconds, d.microseconds)

print(timedelta(hours=24) == timedelta(days=1))
print(timedelta(minutes=1) < timedelta(seconds=90))
print(bool(timedelta(0)))

Internally, a timedelta stores only days, seconds, and microseconds. The constructor normalizes the arguments: 36 hours become one day and 12 hours, a week becomes seven days, and seconds stay below 86400. The repr shows the three stored fields. Durations compare by their length, and a zero duration is false.

$ python create_timedelta.py
2 days, 0:00:00
1 day, 12:00:00
1:30:00
8 days, 0:00:00
0:00:01.500000
1:30:00
8 days, 2:30:00.250000
datetime.timedelta(days=8, seconds=9000, microseconds=250000)
8 9000 250000
True
True
False

seconds versus total_seconds

A frequent mistake is to read the seconds attribute when we want the length of a duration in seconds.

total_seconds.py
from datetime import timedelta

trip = timedelta(days=2, hours=3, minutes=20)

print(trip)
print("seconds:", trip.seconds)
print("total_seconds():", trip.total_seconds())

print("hours:", trip.total_seconds() / 3600)
print("hours:", trip / timedelta(hours=1))
print("minutes:", trip // timedelta(minutes=1))

short = timedelta(milliseconds=1234)
print(short.seconds, short.microseconds, short.total_seconds())

The seconds attribute holds only the part below one day, here 3 hours and 20 minutes, so it ignores the two days. The total_seconds method returns the whole duration as a float. To convert to other units, divide by a timedelta of that unit: true division gives a float, floor division an integer.

$ python total_seconds.py
2 days, 3:20:00
seconds: 12000
total_seconds(): 184800.0
hours: 51.333333333333336
hours: 51.333333333333336
minutes: 3080
1 234000 1.234

Negative durations

Subtracting a later time from an earlier one gives a negative duration. Its printed form surprises many people.

negative_timedelta.py
from datetime import datetime, timedelta

planned = datetime(2026, 11, 19, 9, 0)
actual = datetime(2026, 11, 19, 8, 50)

diff = actual - planned
print(diff)
print(repr(diff))
print(diff.total_seconds())

print(-diff)
print(abs(diff))
print(timedelta(hours=-1))
print(timedelta(days=-1, hours=23) == timedelta(hours=-1))

for arrival in ["08:50", "09:00", "09:25"]:
    t = datetime.combine(planned.date(), datetime.strptime(arrival, "%H:%M").time())
    delay = t - planned
    minutes = int(delay.total_seconds() // 60)
    if delay < timedelta(0):
        print(f"{arrival}  early by {-minutes} min")
    elif not delay:
        print(f"{arrival}  on time")
    else:
        print(f"{arrival}  late by {minutes} min")

Ten minutes early prints as -1 day, 23:50:00. Only the days field can be negative; seconds and microseconds are always positive, so minus ten minutes is stored as minus one day plus 23 hours 50 minutes. The value is correct, as total_seconds shows. To print it, negate it or take abs, and compare with timedelta(0) to get the sign. A zero timedelta is false, which the not delay test uses.

$ python negative_timedelta.py
-1 day, 23:50:00
datetime.timedelta(days=-1, seconds=85800)
-600.0
0:10:00
0:10:00
-1 day, 23:00:00
True
08:50  early by 10 min
09:00  on time
09:25  late by 25 min

Multiplying and dividing

Durations can be multiplied and divided by numbers, and divided by other durations.

timedelta_math.py
from datetime import timedelta

shift = timedelta(hours=7, minutes=30)

print(shift * 5)
print(shift * 1.5)
print(shift / 4)
print(shift // 4)

lap = timedelta(minutes=4, seconds=12)
print(shift / lap)
print(shift // lap)
print(shift % lap)

laps, rest = divmod(shift, lap)
print(laps, rest)

try:
    print(shift + 60)
except TypeError as e:
    print("TypeError:", e)

try:
    print(shift / timedelta(0))
except ZeroDivisionError as e:
    print("ZeroDivisionError:", e)

Multiplying and dividing by a number gives a timedelta. Dividing a duration by another duration gives a float with / and an integer with //: 107 laps fit into the shift. The % operator and divmod return the remainder as a timedelta. Adding a plain number has no unit and raises TypeError; dividing by a zero duration raises ZeroDivisionError.

$ python timedelta_math.py
1 day, 13:30:00
11:15:00
1:52:30
1:52:30
107.14285714285714
107
0:00:36
107 0:00:36
TypeError: unsupported operand type(s) for +: 'datetime.timedelta' and 'int'
ZeroDivisionError: division by zero

Summing durations

To add up a list of durations, we use sum, but with a start value.

work_log.py
from datetime import datetime, timedelta

log = [
    ("2026-11-16", "08:40", "16:55"),
    ("2026-11-17", "09:05", "17:30"),
    ("2026-11-18", "08:15", "15:45"),
    ("2026-11-19", "08:50", "18:20"),
    ("2026-11-20", "09:00", "16:40"),
]

days = []
for day, start, end in log:
    t1 = datetime.fromisoformat(f"{day} {start}")
    t2 = datetime.fromisoformat(f"{day} {end}")
    days.append(t2 - t1)
    print(day, t2 - t1)

try:
    print(sum(days))
except TypeError as e:
    print("TypeError:", e)

total = sum(days, timedelta())
print("total:", total)
print("average:", total / len(days))
print("longest:", max(days))

overtime = total - timedelta(hours=40)
print("overtime:", overtime)

The sum function starts from the integer 0, and 0 plus a timedelta raises TypeError. Passing timedelta() as the start value fixes that. The total of 41 hours 20 minutes prints as 1 day, 17:20:00. Dividing by the number of days gives the average, and max finds the longest day.

$ python work_log.py
2026-11-16 8:15:00
2026-11-17 8:25:00
2026-11-18 7:30:00
2026-11-19 9:30:00
2026-11-20 7:40:00
TypeError: unsupported operand type(s) for +: 'int' and 'datetime.timedelta'
total: 1 day, 17:20:00
average: 8:16:00
longest: 9:30:00
overtime: 1:20:00

Formatting durations

The str form of a timedelta cannot be changed with a format specification. For other forms, we compute the parts with divmod ourselves.

format_timedelta.py
from datetime import timedelta


def hms(delta):
    sign = "-" if delta < timedelta(0) else ""
    seconds = int(abs(delta).total_seconds())
    hours, rest = divmod(seconds, 3600)
    minutes, seconds = divmod(rest, 60)
    return f"{sign}{hours:02}:{minutes:02}:{seconds:02}"


def words(delta):
    sign = "-" if delta < timedelta(0) else ""
    seconds = int(abs(delta).total_seconds())
    parts = []
    for name, size in [("d", 86400), ("h", 3600), ("min", 60), ("s", 1)]:
        count, seconds = divmod(seconds, size)
        if count:
            parts.append(f"{count} {name}")
    return sign + (" ".join(parts) or "0 s")


samples = [
    timedelta(minutes=5, seconds=7),
    timedelta(hours=26, minutes=3),
    timedelta(seconds=-90),
    timedelta(days=3, seconds=45.8),
    timedelta(0),
]

for d in samples:
    print(f"{str(d):>22}  {hms(d):>10}  {words(d)}")

The hms function prints total hours, so 26 hours stay 26 and do not turn into a day. Both functions take the sign first and work with the absolute value, which avoids the -1 day form. Converting to int drops the fractions of a second. The words function skips zero parts.

$ python format_timedelta.py
               0:05:07    00:05:07  5 min 7 s
        1 day, 2:03:00    26:03:00  1 d 2 h 3 min
      -1 day, 23:58:30   -00:01:30  -1 min 30 s
3 days, 0:00:45.800000    72:00:45  3 d 45 s
               0:00:00    00:00:00  0 s

Parsing durations

Configuration files and command line options often contain durations such as 1h 30m. A regular expression turns them into keyword arguments for timedelta.

parse_duration.py
import re
from datetime import timedelta

UNITS = {"w": "weeks", "d": "days", "h": "hours", "m": "minutes", "s": "seconds"}
TOKEN = re.compile(r"(\d+(?:\.\d+)?)\s*([wdhms])")


def parse_duration(text):
    text = text.strip().lower()
    tokens = TOKEN.findall(text)
    if not tokens or TOKEN.sub("", text).strip():
        raise ValueError(f"invalid duration: {text!r}")
    args = {}
    for number, unit in tokens:
        name = UNITS[unit]
        args[name] = args.get(name, 0) + float(number)
    return timedelta(**args)


def parse_clock(text):
    h, m, s = (int(part) for part in text.split(":"))
    return timedelta(hours=h, minutes=m, seconds=s)


for text in ["1h 30m", "2d4h", "45s", "1.5h", "3w", "10 x"]:
    try:
        print(f"{text:8} {parse_duration(text)}")
    except ValueError as e:
        print(e)

print(parse_clock("01:42:07"))
print(parse_clock("30:00:00"))

The TOKEN pattern matches a number followed by a unit letter. If no token matches, or anything is left after removing the tokens, the text is invalid. The parse_clock function reads the HH:MM:SS form. The hours may exceed 23, which strptime would reject.

$ python parse_duration.py
1h 30m   1:30:00
2d4h     2 days, 4:00:00
45s      0:00:45
1.5h     1:30:00
3w       21 days, 0:00:00
invalid duration: '10 x'
1:42:07
1 day, 6:00:00

Rounding datetimes

The modulo operator with a timedelta rounds datetimes to an interval, for example to quarter hours in a booking system.

round_datetime.py
from datetime import datetime, timedelta

EPOCH = datetime(2000, 1, 1)


def floor_dt(dt, step):
    return dt - (dt - EPOCH) % step


def ceil_dt(dt, step):
    rest = (dt - EPOCH) % step
    return dt + (step - rest) if rest else dt


def round_dt(dt, step):
    down = floor_dt(dt, step)
    return down + step if dt - down >= step / 2 else down


quarter = timedelta(minutes=15)
times = ["2026-11-19 08:07:30", "2026-11-19 08:52:10", "2026-11-19 09:00:00"]

for text in times:
    dt = datetime.fromisoformat(text)
    print(f"{dt:%H:%M:%S}  floor {floor_dt(dt, quarter):%H:%M}  "
          f"ceil {ceil_dt(dt, quarter):%H:%M}  round {round_dt(dt, quarter):%H:%M}")

calls = [timedelta(minutes=3, seconds=10), timedelta(seconds=40),
         timedelta(minutes=12, seconds=1)]
minute = timedelta(minutes=1)
billed = [-(-c // minute) for c in calls]
print("billed minutes:", billed, sum(billed))

The remainder of the time since a fixed reference point, divided by the step, tells how far the time is past the last boundary. Subtracting it rounds down; adding the rest of the step rounds up. The reference EPOCH must lie on a boundary; midnight does. For billing, -(-c // minute) is ceiling division: every started minute counts.

$ python round_datetime.py
08:07:30  floor 08:00  ceil 08:15  round 08:15
08:52:10  floor 08:45  ceil 09:00  round 08:45
09:00:00  floor 09:00  ceil 09:00  round 09:00
billed minutes: [4, 1, 13] 18

Months and years

A timedelta has no months or years argument, because months and years differ in length. Adding months needs its own function.

add_months.py
from datetime import date, timedelta


def days_in_month(year, month):
    if month == 12:
        return 31
    return (date(year, month + 1, 1) - timedelta(days=1)).day


def add_months(d, months):
    index = d.year * 12 + d.month - 1 + months
    year, month = divmod(index, 12)
    month += 1
    day = min(d.day, days_in_month(year, month))
    return date(year, month, day)


try:
    timedelta(months=1)
except TypeError as e:
    print("TypeError:", e)

start = date(2026, 1, 31)
print("+30 days: ", start + timedelta(days=30))
print("+1 month: ", add_months(start, 1))

for n in range(1, 7):
    print(n, add_months(start, n))

print(add_months(date(2028, 2, 29), 12))
print(add_months(date(2026, 3, 15), -3))

Thirty days after January 31 is March 2, not the end of February. The add_months function counts months from year 0, adds the offset, and clamps the day to the length of the target month, which is the day before the first of the next month. Negative offsets go back in time. The third-party dateutil library provides the same with relativedelta.

$ python add_months.py
TypeError: timedelta() got an unexpected keyword argument 'months'
+30 days:  2026-03-02
+1 month:  2026-02-28
1 2026-02-28
2 2026-03-31
3 2026-04-30
4 2026-05-31
5 2026-06-30
6 2026-07-31
2029-02-28
2025-12-15

Limits and resolution

A timedelta has a limited range and a resolution of one microsecond.

limits.py
from datetime import date, datetime, timedelta

print(timedelta.min)
print(timedelta.max)
print(timedelta.resolution)

print(timedelta(seconds=0.0000005))
print(timedelta(seconds=0.0000015))
print(timedelta(microseconds=2.5))

try:
    timedelta(days=1_000_000_000)
except OverflowError as e:
    print("OverflowError:", e)

try:
    date(9999, 12, 31) + timedelta(days=1)
except OverflowError as e:
    print("OverflowError:", e)

print(datetime.max - datetime.min)

The days field ranges between minus and plus 999,999,999. Fractions below a microsecond are rounded with round-half-to-even: half a microsecond becomes 0 and one and a half becomes 2. Going beyond the limits raises OverflowError, as does adding a day to the last possible date. The span from datetime.min to datetime.max fits easily.

$ python limits.py
-999999999 days, 0:00:00
999999999 days, 23:59:59.999999
0:00:00.000001
0:00:00
0:00:00.000002
0:00:00.000002
OverflowError: days=1000000000; must have magnitude <= 999999999
OverflowError: date value out of range
3652058 days, 23:59:59.999999

Lap times

The last example computes lap times from the timestamps of a race. It uses subtraction, min, sum with a start value, and custom formatting.

lap_times.py
from datetime import datetime, timedelta

stamps = """
10:00:00.00
10:04:12.35
10:08:20.10
10:12:31.92
10:16:36.48
10:20:49.03
""".split()

times = [datetime.strptime(s, "%H:%M:%S.%f") for s in stamps]
laps = [b - a for a, b in zip(times, times[1:])]


def fmt(delta):
    minutes, seconds = divmod(delta.total_seconds(), 60)
    return f"{int(minutes)}:{seconds:05.2f}"


best = min(laps)
average = sum(laps, timedelta()) / len(laps)

for i, lap in enumerate(laps, 1):
    gap = lap - best
    mark = " best" if lap == best else f" +{gap.total_seconds():.2f}"
    print(f"lap {i}  {fmt(lap)}{mark}")

print("total  ", fmt(times[-1] - times[0]))
print("average", fmt(average))

The timestamps are parsed with %f, which accepts fractions of a second. Pairs of consecutive times from zip give the laps. The fmt function prints minutes and seconds with hundredths, and each lap shows its gap to the best one.

$ python lap_times.py
lap 1  4:12.35 +7.79
lap 2  4:07.75 +3.19
lap 3  4:11.82 +7.26
lap 4  4:04.56 best
lap 5  4:12.55 +7.99
total   20:49.03
average 4:09.81

Source

datetime – timedelta objects

In this article we have worked with durations in Python. See also Python datetime, Python format datetime, and Python zoneinfo, which shows how adding a timedelta behaves across daylight saving time transitions.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.