Working with durations in Python is handled primarily through the timedelta class in the datetime module — a simple yet powerful object representing a difference in time as days, seconds, and microseconds. You can add or subtract timedelta from date or datetime objects to shift dates/times forward or backward, compute the exact interval between two points in time, or measure elapsed durations in logs, benchmarks, timers, scheduling, and analytics. In 2026, mastering timedelta remains essential — it’s used constantly for age calculations, due dates, countdowns, performance timing, data filtering by time windows, and any logic involving time spans — all with precise, timezone-aware arithmetic when combined with zoneinfo.
Here’s a complete, practical guide to working with durations: creating timedelta, date/time arithmetic, computing differences, real-world patterns, and modern best practices with type hints, pandas/Polars integration, and edge-case handling.
Creating a timedelta is straightforward — specify any combination of weeks, days, hours, minutes, seconds, milliseconds, or microseconds.
from datetime import datetime, timedelta
# 2 days, 3 hours, 30 minutes
duration = timedelta(days=2, hours=3, minutes=30)
print(duration) # 2 days, 3:30:00
# Microsecond precision
tiny = timedelta(microseconds=123456)
print(tiny) # 0:00:00.123456
Adding/subtracting durations shifts date or datetime objects — returns a new object, originals unchanged.
dt = datetime(2023, 3, 14, 13, 30, 45)
# Add duration
new_dt = dt + duration
print(new_dt) # 2023-03-16 17:00:45
# Subtract one week
last_week = dt - timedelta(weeks=1)
print(last_week) # 2023-03-07 13:30:45
Differences between two dates/datetimes return a timedelta — access .days, .seconds, .microseconds, or .total_seconds() for precise intervals.
start = datetime(2023, 3, 14, 13, 30, 45)
end = datetime(2023, 3, 16, 17, 0, 0)
delta = end - start
print(delta) # 2 days, 3:29:15
print(delta.days) # 2
print(delta.seconds / 3600) # 3.4875 (hours)
print(delta.total_seconds()) # 182955.0
Real-world pattern: calculating time elapsed, deadlines, or age — very common in user profiles, subscriptions, logs, and reminders.
# Age in years (approximate)
birthdate = date(1990, 5, 15)
today = date.today()
age_days = (today - birthdate).days
age_years = age_days // 365.25
print(f"Age: {age_years:.1f} years") # e.g., 35.7 years
# Days until deadline
deadline = date(2026, 12, 31)
days_left = (deadline - today).days
print(f"Days left: {days_left}")
Best practices make duration work safe, readable, and performant. Use keyword arguments when creating timedelta — timedelta(days=2, hours=3) — clearer and less error-prone than positional. Prefer total_seconds() for precise floating-point durations — avoids integer truncation. Modern tip: use Polars for large timestamp columns — pl.col("end") - pl.col("start") returns duration in days/seconds/microseconds — 10–100× faster than pandas. Add type hints — timedelta — improves readability and mypy checks. Handle negative deltas — if delta.days < 0 for past events. For month/year jumps, use dateutil.relativedelta — dt + relativedelta(months=3) — handles month-end correctly (unlike timedelta). In production, use UTC for all stored timestamps — convert local only for display. Combine with pandas — df['duration'] = df['end'] - df['start'] — vectorized and fast. Wrap arithmetic over user input in try/except — invalid dates raise errors.
Working with durations using timedelta makes time shifts and intervals clean, precise, and reliable — add/subtract time, compute spans, and handle real-world time logic without bugs. In 2026, use keyword args, UTC, type hints, and Polars for scale. Master durations, and you’ll build accurate scheduling, analytics, timers, and time-based features effortlessly.
Next time you need to add days, subtract hours, or find the time between events — reach for timedelta. It’s Python’s cleanest way to do date/time math — accurately and efficiently.