Time difference in seconds (as a floating point)

Question:

>>> from datetime import datetime
>>> t1 = datetime.now()
>>> t2 = datetime.now()
>>> delta = t2 - t1
>>> delta.seconds
7
>>> delta.microseconds
631000

Is there any way to get that as 7.631000 ? I can use time module, but I also need that t1 and t2 variables as DateTime objects. So if there is an easy way to do it with datettime, that would be great. Otherwise it’ll look ugly:

t1 = datetime.now()
_t1 = time.time()
t2 = datetime.now()
diff = time.time() - _t1
Asked By: pocoa

||

Answers:

combined = delta.seconds + delta.microseconds/1E6

Answered By: Edward Dale

I don’t know if there is a better way, but:

((1000000 * delta.seconds + delta.microseconds) / 1000000.0)

or possibly:

"%d.%06d"%(delta.seconds,delta.microseconds)
Answered By: Douglas Leeder

for newer version of Python (Python 2.7+ or Python 3+), you can also use the method total_seconds:

from datetime import datetime
t1 = datetime.now()
t2 = datetime.now()
delta = t2 - t1
print(delta.total_seconds())
Answered By: daniel kullmann
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.