klex52s
klex52s

Reputation: 437

Subtracting Datetime Objects in Python

I am comparing timestamps and the results are not what I expect. For example, I have the following datetimes:

2019-03-04 08:52:00 - 2019-03-04 08:53:00 = -1 day, 23:59:00

I would expect the result to only be a difference of 1 minute. It seems like it's performing a literal subtraction (which is I guess what I'm telling it to do). Instead, how do I find the difference?

Note: It works when the first timestamp is "larger"/occurs later than the second. For reference, the results come from comparing values between two dictionaries, where the values are timestamps and the keys match.

comparison = {(dict1[x], dict2[x]): dict1[x] - dict2[x] for x in dict1 if x in dict2}

Upvotes: 0

Views: 859

Answers (2)

user2357112
user2357112

Reputation: 280181

That is the difference. The difference between the two datetimes you are subtracting is -1 days, 23 hours, and 59 minutes, a.k.a. -1 minutes.

If you want the absolute value of the difference, take the absolute value:

>>> x = datetime.timedelta(minutes=-1)
>>> x
datetime.timedelta(-1, 86340)
>>> abs(x)
datetime.timedelta(0, 60)

Upvotes: 4

Reedinationer
Reedinationer

Reputation: 5774

Since it works if the first value is larger than the other then why not do something like:

def difference_between_dates(date1, date2):
    if date1 > date2:
        return date1 - date2
    else:
        return date2 - date1

Upvotes: 0

Related Questions