How to add time delay in Python?
Last Updated :
07 Apr, 2023
In this article, we are going to discuss how to add delay in Python.
How to add Time Delay?
- In order to add time delay in our program code, we use the sleep() function from the time module. This is the in-built module in Python we don't need to install externally.
- Time delay means we are adding delay during the execution time in our program code. It should be between two statements or between any part of the program code according to you.
Method 1: Using time.sleep() function
Approach:
- Import the time module
- For adding time delay during execution we use the sleep() function between the two statements between which we want the delay. In the sleep() function passing the parameter as an integer or float value.
- Run the program.
- Notice the delay in the execution time.
What is the Syntax of time.sleep
time.sleep(value)
To understand the topic perfectly. Let's see the implementation by taking some examples.
Note: As an output, I have shown the GIF, so that you can notice the time delay in the program code during the execution time.
Example 1: Printing the numbers by adding a time delay.
Python3
# importing module
import time
# running loop from 0 to 4
for i in range(0,5):
# printing numbers
print(i)
# adding 2 seconds time delay
time.sleep(2)
Output:

Example 2: Dramatic printing using sleep() for every character.
Python3
# importing time module
import time
def message(string):
for i in string:
# printing each character of the message
print(i, end="")
# adding time delay of half second
time.sleep(0.5)
# main function
if __name__ == '__main__':
msg = "Its looks like auto typing"
# calling the function for printing the
# characters with delay
message(msg)
Output:

Example 3: Printing the pattern by taking range from the user and adding time delay.
Python3
# importing module
import time
# function to print the pattern
def pattern(n):
for i in range(0, n):
for j in range(0, i+1):
print('*', end=' ')
# adding two second of time delay
time.sleep(0.5)
print(' ')
# main function
if __name__ == '__main__':
# taking range from the user
num = 4
print("Printing the pattern")
# calling function to print the pattern
pattern(num)
Output:

Example 4: Multithreading using sleep()
Python3
# importing
import time
from threading import Thread
# making first thread of Geeks
class Geeks(Thread):
def run(self):
for x in range(4):
print("Geeks")
# adding delay of 2.2 seconds
time.sleep(2.2)
# making second thread of For
class For(Thread):
def run(self):
for x in range(3):
print('For')
# adding delay of 2.3 seconds
time.sleep(2.3)
print("Hello")
# making the object for both the
# threads separately
g1 = Geeks()
f1 = For()
# starting the first thread
g1.start()
# starting the second thread
f1.start()
# waiting for the both thread to join
# after completing their job
g1.join()
f1.join()
# when threads complete their jobs
# message will be printed
print("All Done!!")
Output:

Method 2: Using threading.Event.wait function
The threading.Event.wait procedure, the thread waits until the set() method execution is not complete. Time can be used in it; if a specific time is set, execution will halt until that time has passed; after that, it will resume while the set() of an event is still active.
What is the Syntax of threading.Event.wait function
threading.Event.wait()
Example:
Python3
from time import sleep
if __name__ == '__main__':
# delay in seconds
delay = 2
print('Geeks')
sleep(delay)
print('for')
sleep(delay)
print('Geeks')
Output:
Geeks
for
Geeks
Method 2: Using threading.Timer class
Actions that need to be scheduled to begin at a specific time are represented by timer objects. These items are scheduled to execute on a different thread that performs the action.
What is the Syntax of threading.Timer function
threading.Timer(interval, function)
Example:
Python3
# Program to demonstrate
# timer objects in python
import threading
def gfg():
print("Computer Science: GeeksforGeeks\n")
timer = threading.Timer(1.0, gfg)
timer.start()
print("Timer")
Output:
Timer
Computer Science: GeeksforGeeks
METHOD 4:Using time.monotonic() and time.monotonic_ns() functions:
APPROACH:
The time.monotonic() function returns the value of a monotonic clock, which is not subject to system clock changes. The time.monotonic_ns() function returns the value of the monotonic clock in nanoseconds.
ALGORITHM:
1.Set the value of delay in seconds.
2.Get the current time using time.monotonic() and assign it to start_time.
3.Enter a loop that runs indefinitely.
4.Get the current time again and calculate the elapsed time by subtracting start_time from it.
5.If the elapsed time is greater than or equal to the desired delay, break out of the loop.
6.Print a message indicating that the delay is over.
Python3
import time
start_time = time.monotonic()
delay = 5 # delay in seconds
while True:
current_time = time.monotonic()
elapsed_time = current_time - start_time
if elapsed_time >= delay:
break
print("Time delay of 5 seconds is over!")
OutputTime delay of 5 seconds is over!
The time complexity of this code is O(n) where n is the number of times the loop runs, which depends on the duration of the delay. The auxiliary space is O(1) as it does not require any additional memory.
Similar Reads
How to add Days to a Date in Python?
Python provides an in-built module datetime which allows easy manipulation and modification of date and time values. It allows arithmetic operations as well as formatting the output obtained from the DateTime module. The module contains various classes like date, time, timedelta, etc. that simulate
2 min read
How to Set Time Delay in PHP ?
To set a time delay in PHP, you have several approaches depending on your requirements. The time delay is useful for various purposes like creating a pause in script execution or scheduling tasks. These are the following different approaches: Table of Content Using sleep() FunctionUsing usleep() Fun
2 min read
How to add timestamp to excel file in Python
In this article, we will discuss how to add a timestamp to an excel file using Python. Modules requireddatetime: This module helps us to work with dates and times in Python.pip install datetimeopenpyxl: It is a Python library used for reading and writing Excel files.pip install openpyxltime: This mo
2 min read
How to Measure Elapsed Time in Python
In Python, we can measure the elapsed time (time taken for a specific task to complete) on executing a code segment or a Python script. It's useful when we are benchmarking the code, debugging or optimizing performance. Python provides several built-in modules to measure the execution time of code b
4 min read
How to add timestamp to CSV file in Python
Prerequisite: Datetime module In this example, we will learn How to add timestamp to CSV files in Python. We can easily add timestamp to CSV files with the help of datetime module of python. Let's the stepwise implementation for adding timestamp to CSV files in Python. Creating CSV and adding timest
5 min read
How to add time onto a DateTime object in Python
In Python, adding time (such as hours, minutes, seconds, or days) to a datetime object is commonly done using the timedelta class from the datetime module. This allows precise manipulation of date and time values, including performing arithmetic operations on datetime objects. It's key features incl
3 min read
How to add hours to the current time in Python?
Prerequisites: Datetime module Every minute should be enjoyed and savored. Time is measured by the hours, days, years, and so on. Time helps us to make a good habit of organizing and structuring our daily activities. In this article, we will see how we can extract real-time from a python module. The
3 min read
How to Set Time Delay in JavaScript?
Delaying the execution of code is a fundamental technique that is commonly used in JavaScript for tasks like animations, API polling, or managing time intervals between actions. JavaScript provides several built-in methods to set time delays: setTimeout() and setInterval(). We can set time delay in
2 min read
How to get the duration of audio in Python?
It is possible to find the duration of the audio files using Python language which is rich in the use of its libraries. The use of some libraries like mutagen, wave, audioread, etc. is not only limited to extract the length/duration of the audio files but comes with much more functionality. Source A
5 min read
How to capture SIGINT in Python?
The signal module performs a specific action on receiving signals. Even it has the ability to capture the interruption performed by the user through the keyboard by use of SIGINT. This article will discuss SIGINT only, how to capture it, and what to do after it has been captured. Modules Required: S
3 min read