Python datetime only returning negative numbers?

Question:

I have the following code:

commit_date = get_last_commit_date() # returns datetime obj: 2022-08-25 13:32:12
pr_date = datetime.fromisoformat(ISO_CODE) # returns 2022-08-24 19:15:07

Notice how commit_date is Aug. 25 and pr_date is Aug. 24. I want to find the difference in days which should be 1 day.

Now doing print((pr_date - commit_date).days) will give -1 days. So naturally I swap them and do print((commit_date - pr_date).days) but it reports 0 days? How can it be 0 days? Why isn’t it reporting 1 day time difference?

Asked By: Rohan Shah

||

Answers:

This is a rounding error; since the dates are not at the exact same time, the difference between the two days can end up being on a different day depending on the order you subtract them.

i.e

2022-08-24 19:15:07 - 2022-08-25 13:32:12 = {0}-{0}-{-1} {5}:{42}{55}

and

2022-08-25 13:32:12 - 2022-08-24 19:15:07 = {0}-{0}-{0} {18}:{17}{05}

The difference of hours between 13-19 means the hour is -6. Negative hours in a day means it is a day before, so the difference is 0 days and 18 hours instead of 1 for the second calculation.

If you’re trying to find the difference in days as opposed to total difference in date+time, you wanna subtract the "day" attributes of the individual datetimes as opposed to the entire date+time.

If you do

print((pr_date.day - commit_date.day))
>> -1
print((commit_date.day - pr_date.day))
>> 1

You get the right difference between days. If you use absolute value i.e

print(abs(pr_date.day - commit_date.day))
>> 1

The order of the days doesn’t matter, and you can find the difference like that.