Consider the following code:
>>> import datetime as dt
>>> later_date = dt.datetime.now().replace(hour=18, minute=39, second=59, microsecond=0)
>>> earlier_date = later_date - dt.timedelta(days=1, hours=5, minutes=7, seconds=20)
>>> later_date
datetime.datetime(2025, 8, 31, 18, 39, 59)
>>> earlier_date
datetime.datetime(2025, 8, 30, 13, 32, 39)
The obvious direction
Now I want to get the difference between these two, so essentially the timedelta. The larger minus the smaller one gives me nearly what I expected:
>>> later_date - earlier_date
datetime.timedelta(days=1, seconds=18440)
Now my expectation would have been a day, $5$ hours, $7$ minutes and $20$ seconds. But since $18440$ seconds is the same amount of time, this is fine and correct.
The non-obvious direction
What happens if we subtract the other way round?
My first intuition would be to get a timedelta(days=-1, seconds=-18440)
. Well, not really…:
>>> earlier_date - later_date
datetime.timedelta(days=-2, seconds=67960)
What happens?
After thinking about time a bit, this actually does make sense: $67960 + 18440 = 86400$, which is exactly the number of seconds of one day. So this timedelta can be understood as: “Take your first timestamp, subtract $2$ days and then re-add $67960$ seconds to the result”. Which actually is the same as saying “Subtract one day and then subtract $18440$ seconds”.
Danger!
And now here’s what I find dangerous:
(earlier_date - later_date).seconds
67960
Which means: As a developer, I have to be aware that I have got a negative timedelta, altough the seconds return a positive value!
But a simple solution
It is actually sufficient to just check total_seconds()
:
(earlier_date - later_date).total.seconds()
-104840.0
This again gives me something I can work with.
Again a learning here: Note that the total_seconds method returns a floating point number, as I can have more precision than seconds in a timedelta!