I have written this code where I want that code to run exactly at the minute. However, each iteration take few milliseconds and this causes a small delay in my program. Is there a way to where I can subtract these milliseconds just like the way I have subtracted seconds.
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())
This is the output:
As you can see from the output that with each iteration few milliseconds are added to the time. What I want is to print the exact minute where milliseconds is also zero.
CodePudding user response:
using time.time() instead of 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")
output:
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
there's still offset, but it's less significant than in your output
CodePudding user response:
time.sleep accepts float if you want to sleep for fractions of seconds. That being said I would not expect python to be able to do exact milisecond precision (there is just way too much happening in your system usually for this level of precision).