top

Search

Python Tutorial

.

UpGrad

Python Tutorial

Sleep in Python

Introduction

Python features among the programming languages that are highly in demand and having a command of it can uptick your career. In this blog, we will know everything regarding Sleep in Python. Python’s module called time offers various useful steps to manage time-related functions. One of the well-known methods is sleep (). The Sleep() procedure is detailed in Python 2 as well as 3, and can only halt the present thread without affecting the entire program.

Overview 

On many occasions, you wished your Python code to execute the program quickly. But, at times you wished to pause the execution of some code piece for a slight duration. This function can be smoothly performed over time. sleep () function. In Python, there is an in-built functionality known as sleep() that causes your program to pause or sleep. How to Sleep in Python? This function suspends or delays the execution or running of a present thread for certain specified seconds. 

What Is Sleep() In Python?

The time module of Python offers the time.sleep() function. As already stated above, the Sleep in Python procedure is done to bring some delay or pause in the running of a program. The sleep() process suspends the running of the current thread for specified seconds. The function of python sleep 10 seconds allows a program to be paused for a given time and after the passage of that time, the program is executed automatically.

Example 1

Python sleep() Method
import time
print (“print at once.”)
time.sleep (3)
print (“print after 3 seconds.”)
Run Code

Output

Print at once.
Print after 3 seconds.

This program operates in the following way:

  • “Print at once” is printed

  • time.sleep (3) delays execution for 3 seconds.

  • “Print after 3 seconds” is printed.

Before Python 3.5, the real suspension time may be lower than the argument stated to the time() function.

With the advent of Python 3.5, the delay time will be at best the seconds mentioned

Example 2

Code:

import time
print (“Simple program to demonstrate sleep function:”)
print (“The Start time is as follows : “)
print (time.ctime())
time.sleep ( 5 )
print (“The End time is as follows:” )
print (time.ctime())

Output:

Explanation: In the aforesaid program, we can see that initially we require importing the time module to utilize the sleep() function since it is a time module function in Python. We can view the initial start time as shown utilizing the time module’s ctime() function, which shows the current time. Then we viewed the end time to show utilizing the sleep() function to halt the implementation and then show the current time when the function is halted implementing the thread applying the sleep() function.

Syntax Of Time Sleep()

The syntax for time sleep() method is the following:

time.sleep (t)

Where t is the count in seconds wherein the execution has to be delayed.

Return Value

No value is returned by this method

Example 1: Creating A Time Delay In Seconds

The following code snippet puts a delay of 5 seconds between the two print statements, making the second print statement run 5 seconds after the running of the first print statement:

Import time
Print (“Hello world”)
Time.sleep (5)
Print (“Hello campers”)

Example 2: Creating A Time Delay In Minutes

You can utilize the time module to generate a time delay in minutes. The sleep() function is employed to pause the implementation of the program for a definite number of seconds. In this instance, 5 minutes are equivalent to 5*60 seconds, so the suspension is set to 300 seconds.

From time import sleep

# Sleep for 5 minutes
Print (“Start”)
Sleep (5*60)
Print (“End”)
# Output
# Start
# End

Application of time.sleep()

There are multiple applications of time.sleep(), for instance, we can utilize it to design a pleasant user interface which prints the heading or menu in some fancy manner, nevertheless, one of the essential  applications is to stop a background process which is to be completed in some interval.

The time.sleep Python function is employed to stop the program flow and allow the different technical counterparts to accomplish simultaneously. This function is described in two python versions of 2 and 3 and is part of a module named ‘time’. This function will insert delay to the implementation, which will only stop the completion of the current thread but not the entire program.

Example 1: Creating Time Delay In The Python Loop

# Utilizing the sleep function within a Python loop
# the time module being imported
import time
# the moment when the program begin to be implemented in time
start = time.ctime()
print (start)
for i in range (7)
    # spending time. Utilizing the sleep() technique, halt the execution
    time.sleep(5)
    print(i)
end = time.ctime()
print(end)

Output:

The total time spent surpasses 5 due to the loop’s timeouts of 5-second. The additional time is a function of the thread sequencing of the operating system, the processing time of the program, etc.

Example 2: Creating Time Delay In Python List

# Creating the list
legendaryFootballers = [“Okocha”, “Pele”, “Eusebio”, “Martha”, “Cruyff”,
“ MAradona”]
For legend in legendaryFootballers:
    # Creating the delay
    time.sleep(2)
    # Individual legends in the list will be printed after 2 seconds
    print(legend)

Example 3: Creating Time Delay In Python Tuple

# Time delay in a Python tuple may be inserted employing a Python program.
# The necessary package is currently being imported
Import time
# The program’s starting is being recorded
f = time.ctime()
print(f)
# Creating a recording of the beginning of the program
time.sleep(17)
# The initialization of the Python tuple
my_tuple = (“Time”, “Sleep”, “Python”)
# The tuple is being printed
print(my_tuple)
# The conclusion of the program is being recorded.
e = time.ctime()
print(e)
# Tuple will be presented following 17 seconds of implementation delay.

Example 4: Time Delay In A List Comprehension

Code

# Python program to generate a time delay in a list comprehension
# importing the needed package
import time
# Displaying the starting of the execution
b = time.ctime()
print(b)
# generating and Initializing a list
list = [‘Delay’, ‘Time’, ‘Sleep’, ‘Python’, ‘Time’, ‘Module’]
# a time delay of 10 seconds is added in between generating the list comprehension and printing the components of the list
list = [(time.sleep(10), print(1)) for 1 in list]
# Displaying the completion of the execution
e = time.ctime()
print(e)

Output:

Fri Sep 2 12:46:40 2021
Delay
Time
Sleep
Python
Time
Module
Fri Sep 2 12:56:40 2021

Example 5: Creating Multiple Time Delays

Likewise, you can generate multiple time delays in a program by utilizing multiple time.sleep() function calls, each with a separate delay period. The following is an example of how you can design multiple time delays in a program.

import time
# creating a time delay of 7 seconds
technology =  [‘Spark’, ‘Pyspark’, ‘Java’, ‘Python’]
time.sleep(3)
print(technology)

# Create time delay in python list
for item in technology:
time.sleep(4)
print(item)

# Output
# After the delay of 7 seconds, the list will display
# [‘Spark’, ‘Pyspark’, ‘Java’, ‘Python’]

# Then after every 10 seconds, the items on the list will be displayed
# Spark
# Pyspark
# Java
# Python

Parameters Of Sleep() In Python

Seconds - The number of seconds to pause the implementation of the program. This value can be a floating-point number or an integer.

Example Of Python Sleep()

Here is an instance of a 5-second delay completion of the next line. You need to import time modules to avail the sleep function.

import time
print (“Start : Before sleep”)
time.sleep(5)
print (“End : After sleep”)

Output: In this gif, you can view the delay of the print following line.

Another Example of Python sleep in milliseconds - ms

How will you perform Programming(code) in Python sleep in milliseconds?

It’s simple, you might know 1 second = 1000 milliseconds. Therefore, you need to approve the value in the sleep function similar to that - 1/1000 = .001. You can place a float number within the sleep() function.

Output for that extremely fast, you can view any break time between two print statements.

Import time
print(“Start: Before sleep”)
time.sleep(.001)
print(“End: After sleep”)

Output:

Start: Before sleep

End: After sleep

Return Values Of Sleep() In Python

The python time sleep function does not return anything in general. There is no return of value in this method.

Basic Example of Sleep () In Python

Let us analyze this basic example of sleep() in Python.

In the given code, a pause of 4 seconds is added before the implementation of the 2 print statements.

Code:

import time
print(“Have A Good Day”)
time.sleep(4)
# this will operate after 4 seconds
print(“Can i assist you?”)

Output:

Have A Good Day

Can I assist you?

The above code initially prints the message. Later after a pause of seconds, the next print statement is implemented. In this way we can cause a pause in the code applying time.sleep().

Preferably, sleep() could also be directly imported out of the time module. This makes it easy to avoid the use of time.sleep() each time in our code. Rather, we can just write sleep(4) to generate a pause of 4 seconds. Take a look at the below code for this output.

Code:

from time import sleep
print(“Have A Good Day”)
sleep(4)
# this will operate after 4 seconds
print(“Can i assist you?”)

Output:

Have A Good Day

Can I assist you?

More Examples On Sleep () In Python

Creating A Time Delay Of 3 Minutes In List

Using python3 sleep the list will show up after a pause of 3 minutes

Import time
# creating and Initializing a list
Languages [ ‘C ’ ,  ‘Python’ , ‘C’ ]
# Making a 3 minutes of time delay
time.sleep( 3 * 60)
 print (Languages)

Output:

After a pause of 3 minutes, the list will be viewed as:

[ ‘C ’ ,  ‘Python’ ,  ‘C’ ]

Creating A Digital Clock Using Sleep In Python

import time
while True:
localtime = time.localtime()
result = time.strftime(“%I:%M:%S %p”, localtime)
print(result)
time.sleep(1)

Run Code

Output

2:8:40 PM

2:8:41 PM

2:8:42 PM

2:8:43 PM

2:8:44 PM

… … … 

This example shows the computation and printing of the present local time by creating an infinite loop and applying the while loop. After which, the program delays action for one second. Once more, there is computation of the local time and its printing. This process continues. You obtain an infinite loop if the whole loop contains a condition that is all the time TRUE.

Conclusion

There is vast applicability of the sleep function python in introducing a pause between two successive statements or for pausing for a given duration before running a specific task. Python time.sleep function helps in checking the overloading of the computer system by letting it converge with the earlier operations. 

FAQs

1. Is float accepted by sleep?

There is only one parameter involved in the sleep() function which is seconds. This represents the count in seconds for which the program is to be suspended. The number of seconds can be in float or integer. 

2. Does sleep () permit multi-threading?

Sleep() function accepts time for its argument. It delays the execution of the present thread for the specified amount of seconds in the argument. In applications that are multi-threaded, the function discontinues only the thread you specified to “sleep” explicitly while the other threads continue to execute within the program. 

3. How To Create A Delay In Time In Python?

Here’s how you can create a delay in time in Python:

  1. time.sleep(60) # sleep for one minute.

  2. time.sleep(1)  # sleep for one second.

  3. time.sleep(3600) # sleep for one hour.

Leave a Reply

Your email address will not be published. Required fields are marked *