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.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github