I am organizing a race, and I need a system to scan the bibs of the runners at their arrival. My barcode scanner behave similarly to a keyboard: when I scan something I have a string, in my case name, surname and bib number. So I need a counter that starts when the race starts and I need recording the time of each runner. I tried to use datetime.datetime and time.perf_counter, but the values I get are wrong (I put both and ntp for comparison, I need just one)
import time
from time import ctime
import datetime
import ntplib
#getting time just for comparison purposes
c = ntplib.NTPClient()
response = c.request('pool.ntp.org')
print(ctime(response.tx_time))
start_time_perf = time.perf_counter()
start_time = datetime.datetime.now()
while True:
now_time_perf = time.perf_counter()
now_time = datetime.datetime.now()
elapsed_perf = (now_time_perf - start_time_perf)
elapsed = (now_time - start_time)
barcode = input() # I scan here
now_ntp = c.request('pool.ntp.org')
print(ctime(now_ntp.tx_time))
#print(elapsed_perf)
elapsed_formatted=(time.strftime("%H:%M:%S", time.gmtime(elapsed_perf)))
print(barcode, elapsed, elapsed_formatted)
I have outputs like this one:
Sun Apr 25 16:12:57 2021
Lucy P 13
Sun Apr 25 16:13:02 2021
Lucy P 0:00:00.000010 00:00:00
Jen P 18
Sun Apr 25 16:13:04 2021
Jen P 18 0:00:04.124914 00:00:04
Tiziana D 19
Sun Apr 25 16:13:06 2021
Tiziana D 19 0:00:06.577438 00:00:06
Reka H 17
Sun Apr 25 16:13:07 2021
Reka H 17 0:00:08.096890 00:00:08
Myriam F 20
Sun Apr 25 16:13:12 2021
Myriam F 20 0:00:09.585379 00:00:09
Caroline W 14
Sun Apr 25 16:13:13 2021
Caroline W 14 0:00:15.000074 00:00:15
As you can see the time interval is wrong... Any idea?
Calculating elapsed time right after the user input will fix your issue.
barcode = input() # scan here
elapsed = (now_time - start_time)
Otherwise the amount of time user spending on input will not be added to the difference.