The Python Sleep Function

To delay the execution of a task in Python we can use the sleep() method. sleep() suspends a task for a set period of time in seconds, providing flexibility in how long the task should be delayed for.

 

In this tutorial, we will learn how to use the Python sleep() method with examples.

 

Import the time Package

The sleep method is part of the time package. To use it we will have to import the time package at the top of the Python program like this:

 

import time

 

Using the sleep() method

We can put sleep() somewhere in the local scope of a function or the global scope of a whole program and everything after it will run after the specified delay time.

 

Pass the time in seconds inside the () (parenthesis) of time.sleep(). This can be an integer of seconds or a float for both seconds and milliseconds.

 

import time

print('Running...')
time.sleep(2.5)
print('2.5 seconds later')
Running...
2.5 seconds later

 

Create a Clock in Python

We can put sleep() inside an infinite while loop to make a clock. To get the current time and format it in the function below, import the datetime Python package.

 

import time
from datetime import datetime

def run_clock():
    while True:
        current = datetime.now()
        t = current.strftime("%H:%M:%S")
        print(t, end="", flush=True)
        print("\r", end="", flush=True)
        time.sleep(1)

run_clock()
23:40:49

 

The example above starts an infinite while loop in the run_clock() function by setting the condition to True. On each iteration, a current date object is created before getting formatted in hours minutes and seconds. Then the time is printed and then the output is flushed so on the next iteration the time will be printed in place of the previous time.

 

Get the Start Time and End Time

To get the total time elapsed, set a start time from the current time, run the sleep() statement, then set an end time from the current time and subtract the two times. Let's create a for loop that will sleep for 2.5 seconds on each iterate and get total time it took to run.

 

import time

start_time = time.time()

for i in range(0,5):
    time.sleep(2.5)
    
end_time = time.time()
dur = end_time - start_time

print(dur)
12.516302824020386

 

Set Different sleep Times

To set different sleep durations, we could create a list of times and iterate through them.

 

import time

times = [1, 2, 0.2, 5.7]

for t in times:
    print(f'Sleeping for {t} seconds...')
    time.sleep(t)
Sleeping for 1 seconds...
Sleeping for 2 seconds...
Sleeping for 0.2 seconds...
Sleeping for 5.7 seconds...

 

Conclusion

You now know how to use sleep in Python to delay processes in Python by a fixed amount of time.

sleep delay