Upper limit in Python time.sleep()?

Others have explained why you might sleep for less than you asked for, but didn’t show you how to deal with this. If you need to make sure you sleep for at least n seconds you can use code like:

from time import time, sleep
def trusty_sleep(n):
    start = time()
    while (time() - start < n):
        sleep(n - (time() - start))

This may sleep more than n but it will never return before sleeping at least n seconds.

Leave a Comment