How to Create a Time Delay in Python

You may use the time module in order to create a time delay in Python:

import time

time.sleep(number of seconds of delay)

Here are few examples of time delays:

3 seconds time delay:

import time

time.sleep(3)

3 minutes time delay:

import time

time.sleep(3 * 60)

3 hours time delay:

import time

time.sleep(3 * 3600)

Next, you’ll see how to apply a time delay across different scenarios.

Different Scenarios of Time Delay in Python

Scenario 1: Time Delay with a List

Suppose that you created a list in Python with 5 items:

my_list = ['aaa', 'bbb', 'ccc', 'ddd', 'eee']

Let’s now say that your goal is to place 3 seconds time delay before creating and printing that list.

You may therefore apply the following syntax in Python to achieve that goal:

import time

time.sleep(3)

my_list = ['aaa', 'bbb', 'ccc', 'ddd', 'eee']

print(my_list)

Run the script, and you’ll see the list after 3 seconds:

['aaa', 'bbb', 'ccc', 'ddd', 'eee']

Alternatively, you can place 3 minutes delay (by applying a multiplication of 3 * 60) as captured below:

import time

time.sleep(3 * 60)

my_list = ['aaa', 'bbb', 'ccc', 'ddd', 'eee']

print(my_list)

The list would appear after 3 minutes:

['aaa', 'bbb', 'ccc', 'ddd', 'eee']

Scenario 2: Time Delay with a Loop

You can apply a time delay when iterating over a list.

For example, you can print each item in the list every 3 seconds using a loop:

import time

my_list = ['aaa', 'bbb', 'ccc', 'ddd', 'eee']

for i in my_list:
    time.sleep(3)
    print(i)

Run the script, and you’ll observe that every 3 seconds an item from the list (from the left to the right) would be printed:

aaa
bbb
ccc
ddd
eee

Scenario 3: Multiple Time Delays

Let’s now insert two time delays in the script:

  • 5 seconds time delay before printing the entire list
  • 3 seconds time delay before printing each item in the list
import time

my_list = ['aaa', 'bbb', 'ccc', 'ddd', 'eee']

time.sleep(5)
print(my_list)

for i in my_list:
    time.sleep(3)
    print(i)

Once you run the script in Python, the entire list would be printed after the first 5 seconds (in green), and then every 3 seconds each item within the list would be printed (in yellow):

['aaa', 'bbb', 'ccc', 'ddd', 'eee']
aaa
bbb
ccc
ddd
eee

Scenario 4: Delay with a List Comprehension

You can get the same delay (of 3 seconds to print each item in the list) using a list comprehension:

import time

my_list = ['aaa', 'bbb', 'ccc', 'ddd', 'eee']
my_list = [(time.sleep(3), print(i)) for i in my_list]

And as before, each item in the list would be printed in intervals of 3 seconds:

aaa
bbb
ccc
ddd
eee

You may also want to check the following guide that explains how to add a progress bar in Python.