【问题标题】:Wrong time in time counter in pythonpython中的时间计数器错误
【发布时间】:2021-04-25 14:19:15
【问题描述】:

我正在组织一场比赛,我需要一个系统来扫描参赛者到达时的号码布。 我的条形码扫描仪的行为类似于键盘:当我扫描某些东西时,我有一个字符串,在我的情况下是姓名、姓氏和围兜号码。 所以我需要一个在比赛开始时开始的计数器,我需要记录每个跑步者的时间。 我尝试使用 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

如您所见,时间间隔是错误的... 有什么想法吗?

【问题讨论】:

  • 你能解释一下哪个时间间隔不对吗?
  • 如您所见,计时器从 16:12:57 开始。当我在 16:13:02 扫描 Lucy 时,五秒钟过去了,但计数器显示 00:00:00。当我在 16:13:04 扫描 Jen 时,七秒过去了,但计数器显示 00:00:04 秒的差异......

标签: python datetime time counter barcode


【解决方案1】:

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

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

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

【讨论】:

  • 对不起,你是对的!还是有一点点差别,不过没关系!谢谢
猜你喜欢
  • 2023-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-15
相关资源
最近更新 更多