Consider the following code:
|
|
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:
|
|
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…:
|
|
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:
|
|
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()
:
|
|
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!