HOWTO · Python

How to Subtract Datetime in Python

It introducess how to perform datetime subtraction in Python

On this page

Subtract one datetime object from another with later - earlier. Python returns a timedelta, which represents the elapsed duration between the two values. You can read that duration in days and seconds or convert it to total seconds, minutes, or hours.

Use the datetime Module to Subtract Datetime in Python

The datetime module provides date and time objects. Construct each value with a year, month, and day; hours, minutes, seconds, and microseconds are optional. The example below uses fixed values so its result does not depend on when you run it.

from datetime import datetime

earlier = datetime(2024, 5, 1, 9, 0)
later = datetime(2024, 5, 1, 11, 30)
duration = later - earlier

print(duration)
print(duration.total_seconds())
print(duration.total_seconds() / 60)
print(duration.total_seconds() / 3600)
2:30:00
9000.0
150.0
2.5

The result is a timedelta of two hours and thirty minutes. Its days, seconds, and microseconds attributes describe the duration in normalized parts. For one total elapsed-seconds value, call total_seconds() on the timedelta (not on a datetime). Divide that value by 60 for minutes or by 3,600 for hours. These divisions retain fractional units when the duration does not contain a whole number of minutes or hours.

The days attribute is the whole-day component, while seconds is the remaining seconds component within the normalized duration; neither is a substitute for the total number of seconds. For example, a duration longer than one day can have seconds below 86,400, so use total_seconds() when you need a single count across the entire span. The returned value can be a float when microseconds are present.

If you need whole units, choose a rounding rule explicitly. Converting with int() truncates toward zero; it does not round to the nearest unit. Also, a year is not a fixed duration: treating 365 days as a year is only an approximation, since leap years and calendar-month boundaries change calendar arithmetic. Use an explicit calendar-based interpretation when the question concerns dates such as “one year later,” rather than elapsed seconds.

Subtraction is appropriate when both values can be compared consistently. Naive values (without timezone information) can be subtracted from other naive values. For aware values, normalize both to UTC with astimezone(timezone.utc) when you need elapsed time across timezone transitions. Mixing a naive value with an aware value raises TypeError; assign or convert timezone information deliberately before subtracting.