Adding Delay in Python: A Beginner’s Guide


Python is a high-level programming language that offers a wide range of modules and libraries to developers. As a beginner, there are several concepts you need to understand to write efficient and effective code in Python. One such concept is adding delay in Python.

Delay, also known as sleep, is a function that pauses the execution of a program for a specified amount of time. Adding delay can be useful in various scenarios, such as when you want to simulate real-world processes or when you want to control the flow of your program.

Using datetime module to Delay

Another way to add delay in Python is by using the `datetime` module. The `datetime.timedelta()` function allows you to create time intervals that can be added or subtracted from dates and times.

Here’s an example of how to use the `datetime.timedelta()` function:

from datetime import datetime, timedelta

delay = timedelta(seconds=2)
endtime = + delay
while < endtime:

In this example, we create a time interval of 2 seconds using `timedelta(seconds=2)` and add it to the current time using ` + delay`. We then use a while loop with an empty body (`pass`) to pause the execution until the endtime is reached.

In conclusion, adding delay in Python is a useful concept that can be used in various scenarios. Python provides several ways to add delay, including the `time` module and the `datetime` module. By understanding these concepts, you can write more efficient and effective code in Python.

Why adding delay is important?

When writing Python programs, it is often important to add a delay or pause between certain actions. This is especially true when working with external resources such as APIs or databases. Adding a delay can help prevent overwhelming the resource with too many requests at once, which can lead to errors or slow response times.

Delay can also be useful in cases where you want to control the flow of your program. For example, you may want to wait a few seconds before running a certain block of code to give the user time to read some information on the screen.

Python provides a built-in `time` module that allows you to add delays in your code. The `time.sleep()` function is used to pause the execution of your program for a specified number of seconds.

Here’s an example:

import time

time.sleep(3)  # Pause for 3 seconds

In this example, the program will print “Starting…”, then pause for 3 seconds using `time.sleep(3)`, and finally print “…Finished”. The output will look like this:


By adding a delay using `time.sleep()`, you can ensure that your program runs smoothly and efficiently without overwhelming external resources or confusing users with too much information at once.

The time module in Python

One of the easiest ways to add a delay in Python is by using the time module. The time module provides various time-related functions, including a sleep() function that can be used to suspend execution of a program for a specified period of time.

To use the sleep() function, you first need to import the time module using the import statement:

import time

Once you’ve imported the time module, you can call the sleep() function and pass in the number of seconds you want your program to pause:

time.sleep(5) # Pauses program execution for 5 seconds

In this example, the program will pause for 5 seconds before continuing with its execution.

It’s important to note that when you use the sleep() function, your program will not do anything during the pause. This means that if you have other tasks that need to be performed while waiting, you may need to use threading or other methods to perform those tasks concurrently.

Overall, using the time module in Python is a simple and effective way to add delays in your programs. Whether you’re building a game or a web application, adding delays can help improve user experience and make your code more efficient.

The sleep() function

Python provides a simple way to add delay to your code execution using the `sleep()` function. This function is part of the `time` module in Python, which provides various time-related functions.

To use the `sleep()` function, you need to import the `time` module first. Here’s an example:

import time

time.sleep(2)  # add a 2-second delay

In this example, we imported the `time` module and used the `sleep()` function to add a 2-second delay between the “Starting…” and “…Done!” messages.

The argument passed to the `sleep()` function specifies the number of seconds to pause the execution of your code. You can pass a floating-point number as well to add a fractional number of seconds. For example:

import time

time.sleep(0.5)  # add a 500-millisecond (0.5 second) delay

In this example, we added a 500-millisecond (0.5 second) delay instead of a whole second.

It’s important to note that while your code is paused during the delay, your program won’t respond to any user input or other events. If you need to perform some background tasks while waiting, you can use threads or asynchronous programming.

In summary, adding delay to your Python code is easy with the `sleep()` function from the `time` module. Just import it, pass the desired duration as an argument, and enjoy your well-timed program!

Adding randomness to delay using random()

Sometimes, adding a fixed delay may not be enough in your Python code. You may want to add some randomness to your delay time to make it more realistic or unpredictable. This is where the `random()` function comes in handy.

The `random()` function is a built-in function in Python’s `random` module that returns a random float between 0 and 1. You can use this function to add randomness to your delay time by multiplying it with a scaling factor.

For example, let’s say you want to add a delay between 1 and 5 seconds to your code. You can use the following code:

import random
import time

delay = random.random() * 4 + 1

In the above code, we first import the `random` and `time` modules. We then use the `random()` function to generate a random float between 0 and 1, multiply it by 4 (to get a range of 0 to 4), and add 1 (to get a range of 1 to 5). This gives us a random delay between 1 and 5 seconds.

We then pass this delay value to the `sleep()` function of the `time` module, which pauses the execution of our code for the specified amount of time.

By adding randomness to our delay time, we can make our Python code more dynamic and realistic.

Using timeit() function to measure code execution time

In Python, it is important to measure the execution time of your code. This helps you identify areas of your code that are taking longer to execute and optimize them for better performance. One way to do this is by using the `timeit()` function.

The `timeit()` function allows you to run a piece of code multiple times and measure the average time it takes to execute. This is useful when you want to compare the performance of different implementations of the same algorithm.

Here’s an example of how to use the `timeit()` function:

import timeit

def my_function():
    # code to be measured

# measure execution time of my_function() by running it 1 million times
execution_time = timeit.timeit(my_function, number=1000000)

print(f"Execution time: {execution_time} seconds")

In this example, we import the `timeit` module and define a function called `my_function()` which contains the code we want to measure. We then use the `timeit.timeit()` method to run `my_function()` one million times and measure its execution time. The result is stored in the `execution_time` variable and printed out.

It’s worth noting that the `timeit()` function disables garbage collection by default during the timing. This is done to prevent garbage collection from affecting the timing results. However, if your code creates a lot of garbage, you may want to enable garbage collection during execution by passing `gc.enable()` as a setup argument to `timeit()`.

In conclusion, measuring execution time is an important step in optimizing your Python code for better performance. By using the `timeit()` function, you can easily measure how long it takes for your code to execute and identify areas that need improvement.


In conclusion, adding delay in Python is a simple and useful technique that every beginner should learn. By using the time module, you can easily add delays in your code to control the timing of your program’s execution.

Delaying the execution of a program can be useful for a variety of reasons, such as creating animations, simulating real-world scenarios, or simply adding pauses between different parts of your program.

Remember to use the time.sleep() function to add delays in your code. This function takes a floating-point number as an argument, representing the number of seconds to delay the execution of your program.

Overall, adding delay in Python is a valuable skill that can enhance the functionality and user experience of your programs. So go ahead and start experimenting with delays in your code today!
Interested in learning more? Check out our Introduction to Python course!

How to Become a Data Scientist PDF

Your FREE Guide to Become a Data Scientist

Discover the path to becoming a data scientist with our comprehensive FREE guide! Unlock your potential in this in-demand field and access valuable resources to kickstart your journey.

Don’t wait, download now and transform your career!

Pierian Training
Pierian Training
Pierian Training is a leading provider of high-quality technology training, with a focus on data science and cloud computing. Pierian Training offers live instructor-led training, self-paced online video courses, and private group and cohort training programs to support enterprises looking to upskill their employees.

You May Also Like

Deep Learning, Tutorials

ChatGPT API Python Guide

Introduction Welcome to this tutorial on using the ChatGPT API from OpenAI with Python! ChatGPT is a state-of-the-art language model that can generate human-like responses to text-based inputs. With its ability to understand context and generate coherent responses, ChatGPT has become a popular tool for chatbots and conversational agents in a variety of industries. In […]

Python Basics, Tutorials

Using Min Function in Python

Introduction Python is a powerful programming language that can be used for a variety of tasks, including data analysis and manipulation. One common task in data analysis is finding the smallest number in a list, which one can do in a variety of ways, including using the Python min function. In this tutorial, we will […]

Python Basics, Tutorials

Understanding the Max Python Function

Introduction Lists are an important data structure in Python programming. They allow us to store a collection of values in a single variable. Sometimes we need to find the maximum value in a list, in this blog post we’ll cover how to use the max python function. This can be useful in many situations, for […]