Is sleep function is not accurete in python?

Is there a better solution instead for using the sleep command with pyhton on a raspberry pi board?
My python program has sleep(1), which means one second delay and when the code has run for 3600 times it runs a MySQL insert command.
The problem is that the “delay” is not of all accurate. It may be a 1-2 minutes difference after every 3600 seconds when it runs the MySQL insert command.

Some info about my environment.
Python version: 3.10.12
Ubuntu version: 22.04.4 LTS
Board version: Raspberry Pi 4 Model B Rev 1.5

You are not considering the time taken to execute the code between sleeps, which accounts for the 1-2 minute discrepancy.

You can keep track of the time and calculate how long to the next second.
Then on average you will tick at 1 second intervals.

target_time = time.time()
target_time += 1
time_to_next_second = target_time - time.time() 
# does not account for -ive wait
1 Like