How do I make a time delay in Python?

Better Stack Team
Updated on January 26, 2023

There are a few ways to make a time delay in Python. Here are three options:

  1. time.sleep(): You can use the sleep() function from the time module to add a delay to your program. The sleep() function takes a single argument, which is the number of seconds to delay the program. For example:
 
import time

print("Hello")
time.sleep(2)
print("World")

This will print "Hello", delay for 2 seconds, and then print "World".

  1. datetime.timedelta(): You can use the timedelta class from the datetime module to represent a duration of time, and then add that duration to a specific point in time to calculate a future point in time. For example:
 
import datetime

current_time = datetime.datetime.now()
delay = datetime.timedelta(seconds=2)
future_time = current_time + delay

print("Hello")
while datetime.datetime.now() < future_time:
    # Do nothing
print("World")

This will print "Hello", delay for 2 seconds, and then print "World".

  1. Loop and time.perf_counter(): You can use a loop and the perf_counter() function from the time module to create a delay by repeatedly checking the current time and comparing it to a future point in time. For example:
 
import time

print("Hello")
end_time = time.perf_counter() + 2
while time.perf_counter() < end_time:
    # Do nothing
print("World")

This will print "Hello", delay for 2 seconds, and then print "World".

Note that all of these options will cause the program to "block", meaning that it will not be able to do anything else while the delay is happening. If you need to be able to do other things while the delay is happening, you might want to consider using a timer or a separate thread to perform the delay.

Also, the first option is recommended if you don’t want to waste CPU time by busy waiting. The sleep function will block the current thread while it is sleeping and leaves the waking up to the scheduler.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →

Reliability is the
ultimate feature

Delightful observability tools that turn your logs & monitoring into a secret weapon for shipping better software faster.

Explore Better Stack