To pause a program (thread)
import time
time.sleep(<number of seconds you want to stop the programme>)
- If you give 1, it will stop for 1 second.
- If you give 0.5, it will stop for 0.5 seconds.
- If you give 0.001 it will stop for 0.001 seconds.
- The argument type is float.
- Only the thread calling the sleep function will stop.
- The accuracy depends on the environment (operating system, hardware, CPU load, etc.).
Example program
The example program stops for 1.5 seconds using the time.sleep function and displays the elapsed time. The time.time function used in the example program is a function that returns the elapsed seconds since 1 January 1970, called epoch seconds (UNIX time). This is used to measure the execution time of the sleep function.import time
# Get epoch seconds (UNIX time) before sleep
startSec = time.time()
# Stop for 1.5 seconds
time.sleep(1.5)
# Calculate and display how long it has been asleep
print(time.time() - startSec)
References
Test Environment
- Python 3.9.0 (tags/v3.9.0:9cf6752, Oct 5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] on win32
- Microsoft Windows 10 Pro Version 20H2 OS Build 19042.804 Experience: Windows Feature Experience Pack 120.2212.551.0