When executing scripts, you often need to adjust the interval of API requests or add wait times between periodic tasks. In Python, you can pause the execution of a program for a specified duration using the sleep() function included in the standard time library.
This article explains the basic usage of time.sleep() and how to specify time using integers and decimals.
Basic Syntax of time.sleep()
To use time.sleep(), you must first import the module by writing import time. The argument specifies the wait time in seconds.
Syntax:
import time
time.sleep(seconds)
When this function is executed, the program stops for the specified time at that line, and proceeds to the next line of processing once the time has elapsed.
Specific Usage Examples
1. Specifying Seconds with Integers (int)
Here is an example of waiting for a few seconds, such as waiting for a server reconnection or completion. Here, we wait for 3 seconds.
import time
print("Attempting to connect to the server...")
# Wait for 3 seconds
time.sleep(3)
print("Connection successful. Resuming process.")
Output:
Attempting to connect to the server...
(Pauses for 3 seconds here)
Connection successful. Resuming process.
2. Specifying Seconds with Decimals (float)
The argument for time.sleep() accepts not only integers but also floating-point numbers (float). This allows for fine-grained waiting of less than a second, such as 0.1 or 0.5 seconds.
The following example displays list elements sequentially at 0.5-second intervals, simulating a loading process.
import time
loading_steps = ["Initializing", "Loading Config", "Connecting DB", "Done"]
print("--- Application Start ---")
for step in loading_steps:
print(f"Status: {step}")
# Wait for 0.5 seconds
time.sleep(0.5)
print("--- Startup Complete ---")
Output:
--- Application Start ---
Status: Initializing
(Waits 0.5s)
Status: Loading Config
(Waits 0.5s)
Status: Connecting DB
(Waits 0.5s)
Status: Done
--- Startup Complete ---
Note: Accuracy of Wait Time
The time specified in time.sleep() is merely the “minimum wait time.” Since it is affected by the Operating System’s (OS) task scheduling and current system load, the pause may last slightly longer than specified. Please note that it is not suitable for processes requiring strict real-time performance (such as millisecond-level precision control).
Summary
- To pause processing in Python, import the
timemodule and usetime.sleep(seconds). - You can specify not only integers but also decimals (e.g.,
0.5) as arguments. - It is widely used for API rate limiting, reducing load in loops, and creating user interface effects.
