Pandas timedelta subtraction returns different values when operands are swapped

Question:

I have two pd.Timestamp objects:

t1 = pd.Timestamp(2022-11-02 10:44:22.700000)
t2 = pd.TImestamp(2022-11-02 10:44:22.760000)

Now I want to get the timedelta for those two values.
If I do it like this:

t2 - t1

I get Timedelta('0 days 00:00:00.060000'), which is the expected behaviour,
but If I do:

t1 - t2

I get Timedelta('-1 days +23:59:59.940000'), which seems a bit weird as the difference between both is still 0.6 seconds.

Can I avoid this behavior somehow? I don’t want to check which is the bigger value before getting the Timedelta.

Asked By: jsiller

||

Answers:

You can use abs (absolute value) to get the magnitude of the difference:

>>> import pandas as pd
>>> t1 = pd.Timestamp('2022-11-02 10:44:22.700000')
>>> t2 = pd.Timestamp('2022-11-02 10:44:22.760000')
>>> t2 - t1
Timedelta('0 days 00:00:00.060000')
>>> t1 - t2
Timedelta('-1 days +23:59:59.940000')
>>> abs(t1 - t2)
Timedelta('0 days 00:00:00.060000')
Answered By: SNygard
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.