Python sleep function belongs to the time module of python. Python time sleep has a use for add dealy of program execution. You can stop time or halt the program for a Second or Milliseconds using time.sleep() function.
In this tutorial, you will learn about Python sleep function with sleep for Second and Millisecond’s examples.
Python time sleep function only stops the execution of the current thread only, not the whole program or application.
It’s a very simple syntax for python sleep function, you need just import time modules.
Python sleep function Example
Here is an example of a 5-second delay execution of the next line. You have to import time modules to use the sleep function.
import time print("Start : Before sleep") time.sleep(5) print("End : After sleep")
Output: Here is gif, you can see delay of the print next line.
Another Example of Python sleep milliseconds – ms
You have seen the example of Python sleep in second, so how you will do Programming(code) in Python sleep milliseconds.
it’s easy, you may know 1 second = 1000 milliseconds. So you have to pass the value in sleep function like that –
1/1000 = .001. You can put a float number in the sleep() function.
Output for that very fast, you can see any break time between 2 print statements.
import time print("Start: Before sleep") time.sleep(.001) print("End: After sleep")
Output: Start: Before sleep
End: After sleep
Example Sleep time with for loop
For this example, we are running a “for loop” for per second and print the current time.
import time for i in [1, 2, 3, 4]: print("After for %s seconds" % i, end='' + '\n') print("Current Time:", time.asctime(time.localtime(time.time()))) time.sleep(i)
After for 1 seconds
Current Time: Tue Oct 23 13:26:57 2018
After for 2 seconds
Current Time: Tue Oct 23 13:26:58 2018
After for 3 seconds
Current Time: Tue Oct 23 13:27:00 2018
After for 4 seconds
Current Time: Tue Oct 23 13:27:03 2018
QA: How to make a time delay in Python 3?
To make a dealy execution in a program or application you have to use the sleep() function in python. For it, you have to import a time module like this or the above example.
You can put a float argument for sub-second or milliseconds resolution.
from time import sleep sleep(0.1) # Time in seconds.
Side notes: Do comment if you have any doubt or suggestion or examples.
Note: This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
All Python time sleep function and sleep milliseconds examples in Python 3, so it may change its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.