我已經撰寫了這段代碼,我希望該代碼能夠立即運行。但是,每次迭代需要幾毫秒,這會導致我的程式出現小延遲。有沒有辦法像我減去秒的方式一樣減去這些毫秒。
import pandas as pd
import datetime as dt
import time
while True:
now = dt.datetime.now()
current_time = now.strftime('%Y-%m-%d %H:%M:%S')
seconds = int(current_time[-2:])
sleep_sec = 60 - seconds
time.sleep(sleep_sec)
print(dt.datetime.now())
這是輸出:

從輸出中可以看出,每次迭代都會向時間添加幾毫秒。我想要的是列印毫秒也為零的確切分鐘。
uj5u.com熱心網友回復:
使用 time.time() 而不是 time.sleep()
import time
import datetime as dt
start_time = time.time()
while True:
if time.time() - start_time > 60:
# if 60 seconds pass do something
print(dt.datetime.now())
start_time = time.time()
print("60 seconds passed")
輸出:
2021-12-24 12:48:30.542806
60 seconds passed
2021-12-24 12:49:30.543792
60 seconds passed
2021-12-24 12:50:30.544508
60 seconds passed
2021-12-24 12:51:30.544826
60 seconds passed
2021-12-24 12:52:30.545028
60 seconds passed
2021-12-24 12:53:30.545661
60 seconds passed
2021-12-24 12:54:30.546452
60 seconds passed
仍然存在偏移,但它不如您的輸出重要
uj5u.com熱心網友回復:
如果您想睡眠幾分之一秒, time.sleep 接受浮動。話雖如此,我不希望python能夠做到精確的毫秒級精度(通常在您的系統中發生這種精度級別的事情太多了)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/394785.html
下一篇:Python中特定年份的時差
