Durations with timedelta

datetime · Essentials · 8 min

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 + timedelta and date + timedelta give a later moment or day.
  • datetime - datetime gives a timedelta.
  • Timedeltas add, subtract, multiply by numbers and divide: td / timedelta(hours=1) gives hours as a float, and td // 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)  # 30

Remember

  • timedelta is a duration; datetime minus datetime gives one
  • Use total_seconds() or divide by a timedelta, never .seconds for totals
  • timedelta has no months or years

Watch out for

  • Reading td.seconds as the total duration; it drops the days component.

Check yourself

  1. td = timedelta(days=2, hours=3). What is td.seconds?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: docs.python.org/3/library/datetime.html#timedelta-objects