Python time.sleep method explanation with Example

How to sleep in python using time.sleep() method :

In python, we have one method to pause the execution of a program : ‘sleep()‘. This method is available in ‘time’ module. In this tutorial, we will learn how to pause a program for a specific time interval using sleep.

Syntax of Python time.sleep() :

time.sleep(secs)

Explaination :

Only argument we are passing here is ‘secs’ which is the time interval in seconds we want to sleep the program. ‘secs’ is a floating value. That means if we pass ‘.5’ , it will sleep for 500 miliseconds.

Simple example of time.sleep():

import time

print ("Starting the program...")

time.sleep(3)

print("Sleeped for 3 seconds")

If we run the above program, it will print the first line, then next it will sleep for 3 seconds and then after 3 seconds , it will print the last statement. We can also print the time before and after sleep. This will help us to check the exact time it sleeps :

time.sleep() with printing time :

import time

print ("Starting the program...")

print ("Start time : ",time.strftime("%H:%M:%S"))
time.sleep(3)
print ("End time : ",time.strftime("%H:%M:%S"))

print("Sleeped for 3 seconds")

Output :

Starting the program...
Start time :  18:46:48
End time :  18:46:51
Sleeped for 3 seconds

So, it slept for exactly 3 seconds.

Similar tutorials :