290

There has to be an easier way to do this. I have objects that want to be refreshed every so often, so I want to record when they were created, check against the current timestamp, and refresh as necessary.

datetime.datetime has proven to be difficult, and I don't want to dive into the ctime library. Is there anything easier for this sort of thing?

7 Answers 7

747

if you want to compute differences between two known dates, use total_seconds like this:

import datetime as dt

a = dt.datetime(2013,12,30,23,59,59)
b = dt.datetime(2013,12,31,23,59,59)

(b-a).total_seconds()

86400.0

#note that seconds doesn't give you what you want:
(b-a).seconds

0

8
  • 150
    The `note' is the most important part which people miss. I wish I could give another up vote on it.
    – Dexter
    Sep 15, 2013 at 19:59
  • There are times where I notice it gives a seemingly...incorrect result. 59.800 seconds for a split second difference. So, for smaller operations, such as difference of seconds, milliseconds, or microseconds, one could use (b-a).microseconds and then divide that to get the seconds (1000000) or milliseconds (1000) May 26, 2017 at 16:22
  • it appears the value is always positive, even when a and b are swapped
    – Nickpick
    Mar 10, 2018 at 0:02
  • 6
    This helped a lot. But why does python always give the wrong answer for (b-a).seconds?
    – enchance
    Jun 27, 2021 at 13:23
  • 6
    @enchance it's because (b-a).seconds mean only seconds part of the difference. There are also (b-a).minutes , (b-a).hours, ...
    – Septacle
    Jul 2, 2021 at 16:19
49
import time  
current = time.time()

...job...
end = time.time()
diff = end - current

would that work for you?

1
  • 3
    +1; we don't really care about the date of either invocation - we care about the elapsed time. So just use a raw timestamp, as shown. Dec 6, 2010 at 1:58
21
>>> from datetime import datetime

>>>  a = datetime.now()

# wait a bit 
>>> b = datetime.now()

>>> d = b - a # yields a timedelta object
>>> d.seconds
7

(7 will be whatever amount of time you waited a bit above)

I find datetime.datetime to be fairly useful, so if there's a complicated or awkward scenario that you've encountered, please let us know.

EDIT: Thanks to @WoLpH for pointing out that one is not always necessarily looking to refresh so frequently that the datetimes will be close together. By accounting for the days in the delta, you can handle longer timestamp discrepancies:

>>> a = datetime(2010, 12, 5)
>>> b = datetime(2010, 12, 7)
>>> d = b - a
>>> d.seconds
0
>>> d.days
2
>>> d.seconds + d.days * 86400
172800
5
  • 1
    If you return d.seconds + d.days * 86400 instead, it's correct for multiple days ;)
    – Wolph
    Dec 6, 2010 at 1:40
  • 9
    Note that, in the general case, this is not correct. Consider the case a - b, where a is before b (ie, so the result will be negative): (a - b).seconds == 86282 while a - b == datetime.timedelta(-1, 86276, 627665). The correct method, I believe, is to use timedelta.total_seconds()… But that is py2.7+ only. Aug 10, 2011 at 16:19
  • 9
    Indeed, the answer is not right and should reflect @DavidWolever comment. The correct answer is: use timedelta.total_seconds(). Downvoted accordingly. Jun 15, 2013 at 14:16
  • 3
    Upvoted for Python 2.6 answer. total_seconds() is a 2.7+ feature. Feb 13, 2014 at 23:55
  • @JoeHolloway I guess that this isn't working correctly in Python 2.6 too. Apr 23, 2018 at 7:52
12

We have function total_seconds() with Python 2.7 Please see below code for python 2.6

import datetime
import time  

def diffdates(d1, d2):
    #Date format: %Y-%m-%d %H:%M:%S
    return (time.mktime(time.strptime(d2,"%Y-%m-%d %H:%M:%S")) -
               time.mktime(time.strptime(d1, "%Y-%m-%d %H:%M:%S")))

d1 = datetime.now()
d2 = datetime.now() + timedelta(days=1)
diff = diffdates(d1, d2)
2

Here's the one that is working for me.

from datetime import datetime

date_format = "%H:%M:%S"

# You could also pass datetime.time object in this part and convert it to string.
time_start = str('09:00:00') 
time_end = str('18:00:00')

# Then get the difference here.    
diff = datetime.strptime(time_end, date_format) - datetime.strptime(time_start, date_format)

# Get the time in hours i.e. 9.60, 8.5
result = diff.seconds / 3600;

Hope this helps!

2

Another approach is to use timestamp values:

end_time.timestamp() - start_time.timestamp()
0

By reading the source code, I came to a conclusion: the time difference cannot be obtained by .seconds:

@property
def seconds(self):
    """seconds"""
    return self._seconds

# in the `__new__`, you can find the `seconds` is modulo by the total number of seconds in a day
def __new__(cls, days=0, seconds=0, microseconds=0,
            milliseconds=0, minutes=0, hours=0, weeks=0):
    seconds += minutes*60 + hours*3600
    # ...
    if isinstance(microseconds, float):
        microseconds = round(microseconds + usdouble)
        seconds, microseconds = divmod(microseconds, 1000000)
        # ! 👇
        days, seconds = divmod(seconds, 24*3600)
        d += days
        s += seconds
    else:
        microseconds = int(microseconds)
        seconds, microseconds = divmod(microseconds, 1000000)
        # ! 👇
        days, seconds = divmod(seconds, 24*3600)
        d += days
        s += seconds
        microseconds = round(microseconds + usdouble)
    # ...

total_seconds can get an accurate difference between the two times

def total_seconds(self):
    """Total seconds in the duration."""
    return ((self.days * 86400 + self.seconds) * 10**6 +
        self.microseconds) / 10**6

in conclusion:

from datetime import datetime
dt1 = datetime.now()
dt2 = datetime.now()

print((dt2 - dt1).total_seconds())

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.