首页 > 解决方案 > python中的时间计数器错误

问题描述

我正在组织一场比赛,我需要一个系统来扫描参赛者到达时的号码布。我的条形码扫描仪的行为类似于键盘:当我扫描某些东西时,我有一个字符串,在我的情况下是姓名、姓氏和围兜号码。所以我需要一个在比赛开始时开始的计数器,我需要记录每个跑步者的时间。我尝试使用 datetime.datetime 和 time.perf_counter,但我得到的值是错误的(我将两者和 ntp 用于比较,我只需要一个)

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)

我有这样的输出:

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

如您所见,时间间隔是错误的……知道吗?

标签: pythondatetimetimecounterbarcode

解决方案


在用户输入后立即计算经过的时间将解决您的问题。

barcode = input() # scan here
elapsed = (now_time - start_time)

否则用户在输入上花费的时间将不会被添加到差异中。


推荐阅读