3

im using Python v2.x on Windows 64bit

I would like to record two moments in real time and calculate the time span. Please see code as following:

current_time1 = datetime.datetime.now().time() # first moment

# ... some statement...some loops...take some time...

current_time2 = datetime.datetime.now().time() # second moment

time_span = current_time1 - current_time2

Apparently the last line is not executable because current_time is not integer, so my question is, how to convert this statement to integer to do the math? Convert to seconds is my first thought...

Ehtesh Choudhury
  • 7,452
  • 5
  • 42
  • 48
Amber.G
  • 1,343
  • 5
  • 12
  • 16
  • 3
    Already answered there: [datetime example](http://stackoverflow.com/questions/766335/python-speed-testing-time-difference-milliseconds) and there [timeit example](http://stackoverflow.com/questions/7370801/measure-time-elapsed-in-python) – erhesto Feb 11 '16 at 23:12

4 Answers4

8

Subtracting a one datetime.datetime.now() from another gives you a datetime.timedelta instance. If you run dir() on it, you will likely find some useful functions.

>>> x = datetime.datetime.now()
# wait a second or two or use time.sleep()
>>> y = datetime.datetime.now()
>>> z = y - x
>>> type(z)
<type 'datetime.timedelta'>
>>> print(list(filter(lambda x: not x.startswith("_"), dir(z))))
['days', 'max', 'microseconds', 'min', 'resolution', 'seconds', 'total_seconds']
>>> print(z.total_seconds())
2.31
Goodies
  • 4,439
  • 3
  • 31
  • 57
4
current_time1 = datetime.datetime.now()
time.sleep(50)
current_time2 = datetime.datetime.now()

print (current_time2 - current_time1)

or alternatively

time1 = time.time()
time.sleep(50)
time2 = time.time()
print("%s seconds"%(time2-time1))
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
0
import time

current_time1 = time.clock()
do_something()
current_time2 = time.clock()
print "%.2gs" % (current_time2-current_time1)

EDIT:

from datetime import datetime, date

datetime.combine(date.today(), current_time2) - datetime.combine(date.today(), current_time1)
PRVS
  • 1,612
  • 4
  • 38
  • 75
  • oops, got an error: TypeError: unsupported operand type(s) for -: 'datetime.time' and datetime.time – Amber.G Feb 11 '16 at 23:22
  • Try this: `from datetime import datetime, date datetime.combine(date.today(), current_time2) - datetime.combine(date.today(), current_time1)` – PRVS Feb 11 '16 at 23:23
-1

In python 3.x use time.perf_counter

import time

t1_start = time.perf_counter()

do_something() # your code goes here

t1_stop = time.perf_counter()
print("Elapsed time:", t1_stop - t1_start) # print performance indicator
Rian Finnegan
  • 192
  • 1
  • 8