30
>>> 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
mskfisher
  • 3,291
  • 4
  • 35
  • 48
pocoa
  • 4,197
  • 9
  • 37
  • 45

3 Answers3

50

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())
Miraj50
  • 4,257
  • 1
  • 21
  • 34
daniel kullmann
  • 13,653
  • 8
  • 51
  • 67
24

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

Edward Dale
  • 29,597
  • 13
  • 90
  • 129
  • or combined = delta.seconds + (float(1) / delta.microseconds) – pocoa May 21 '10 at 16:22
  • 1
    @pocoa - this is actually an incorrect conversion. 1/time is a rate (Hz) which really doesn't make sense here. this also clearly provides a different result than the accepted answer on which you commented. – underrun Oct 07 '16 at 15:31
7

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)
Mike Graham
  • 73,987
  • 14
  • 101
  • 130
Douglas Leeder
  • 52,368
  • 9
  • 94
  • 137