Subtract one datetime object from another—delta = end_dt - start_dt—to obtain a datetime.timedelta object, then call delta.total_seconds() for the exact elapsed duration in seconds (or divide by 60, 3600, or 86400 for minutes, hours, or fractional days), avoiding delta.seconds alone because .seconds only returns the intra-day remainder (0–86399) and ignores whole days.
Basic Example
from datetime import datetime
start_dt = datetime(2026, 11, 28, 14, 30, 0)
end_dt = datetime(2026, 11, 29, 16, 45, 30)
# 1. Recommended: Subtract `datetime` objects to get a `timedelta`
delta = end_dt - start_dt
print(delta)
# Output: 1 day, 2:15:30
# 2. Exact total elapsed time in seconds, minutes, and hours:
total_sec = delta.total_seconds()
print(f"Total seconds: {total_sec}") # Output: 94530.0
print(f"Total minutes: {total_sec / 60}") # Output: 1575.5
print(f"Total hours: {total_sec / 3600:.2f}") # Output: 26.26
# 3. Decompose `total_seconds()` into clean Days, Hours, Minutes, Seconds:
days = delta.days
hours, remainder = divmod(delta.seconds, 3600)
minutes, seconds = divmod(remainder, 60)
print(f"{days}d {hours}h {minutes}m {seconds}s")
# Output: 1d 2h 15m 30s
Key Details & Edge Cases
- Never confuse
delta.total_seconds()withdelta.seconds:- A
timedeltastores time internally in three normalized fields:.days,.seconds(0to86399), and.microseconds(0to999999). For a 26-hour difference (1 day, 2:00:00),delta.secondsreturns7200(2 hours, dropping the 24-hour day!), whereasdelta.total_seconds()returns93600.0(the full 26 hours). Always use.total_seconds()unless you are explicitly decomposing remainder hours/minutes after reading.days.
- A
- Both
datetimeobjects must be either naive or timezone-aware (TypeError):- Subtracting a timezone-aware
datetime(e.g.,datetime.now(timezone.utc)) from a timezone-naivedatetime(datetime.now()) raisesTypeError: can't offset-naive and offset-aware datetimes. Always work with timezone-aware UTC timestamps (datetime.now(timezone.utc)) or attach a timezone with.replace(tzinfo=timezone.utc)before subtracting.
- Subtracting a timezone-aware
- Daylight Saving Time (DST) accuracy (
zoneinfovs. naive localdatetime):- Subtracting two naive local
datetimeobjects performs pure wall-clock arithmetic and ignores DST spring-forward/fall-back transitions. For real-world elapsed duration across DST changes, construct timezone-aware objects usingzoneinfo.ZoneInfo("America/New_York")and convert both to UTC (.astimezone(timezone.utc)) before subtracting—Python 3.9+ requires UTC conversion sotimedeltameasures true physical elapsed time rather than wall-clock skew.
- Subtracting two naive local
- Negative
timedeltanormalization whenend_dt < start_dt:- If
end_dtis earlier thanstart_dtby 1 hour,delta.daysis-1anddelta.secondsis82800(+23hours, because-1 day + 23 hours = -1 hour), whiledelta.total_seconds()is-3600.0. Wrap withabs(end_dt - start_dt)before formatting into human-readabled/h/m/scomponents so negative values display cleanly.
- If
- Measuring code execution duration (
time.perf_counter()vs.datetime.now()):- Do not use
datetime.now()to benchmark code execution speed, because system clock adjustments (NTP syncs or manual clock changes) can jump forward or backward. Usetime.perf_counter()for high-resolution monotonic benchmarking.
- Do not use
Comparison of timedelta Attributes & Time-Difference Techniques
| Expression / Method | Accounts for Multi-Day Spans? | Return Type | Includes Microseconds? | Best Used When |
|---|---|---|---|---|
delta.total_seconds() (Recommended) |
Yes | float |
Yes (fractional part) | Computing total elapsed seconds, minutes (/ 60), hours (/ 3600), or comparing durations. |
delta.days |
Yes (whole 24-hour periods) | int |
No (truncates toward $-\infty$) | Getting the integer number of complete 24-hour days elapsed. |
divmod(delta.seconds, 3600) (paired with delta.days) |
No (delta.seconds is 0–86399 only) |
tuple[int, int] |
No (use delta.microseconds separately) |
Formatting a timedelta into human-readable "Xd Yh Zm Ws" strings (after abs(delta)). |
time.perf_counter() difference |
N/A (monotonic seconds) | float |
Yes (nanosecond precision) | Benchmarking function runtime or latency without system-clock drift. |
You must log in or register to comment.
