Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pandas timedelta subtraction returns different values when operands are swapped

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading