简体   繁体   中英

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}

That is the difference. The difference between the two datetimes you are subtracting is -1 days, 23 hours, and 59 minutes, aka -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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM