How do I check the difference, in seconds, between two dates? How do I check the difference, in seconds, between two dates? python python

How do I check the difference, in seconds, between two dates?


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

import datetime as dta = 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


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

would that work for you?


>>> from datetime import datetime>>>  a = datetime.now()# wait a bit >>> b = datetime.now()>>> d = b - a # yields a timedelta object>>> d.seconds7

(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.seconds0>>> d.days2>>> d.seconds + d.days * 86400172800