Definition
A built-in module for retrieving the system clock and pausing program execution.
Why It Matters
The time module is the ‘clock’ of your automation. Without it, scripts would run at full speed, potentially overwhelming APIs, failing due to race conditions, or making performance profiling impossible. It provides the temporal control necessary for reliable, real-world software.
Core Concepts
- Epoch Timestamps:
time.time()returns a float of seconds since the Unix Epoch (Jan 1, 1970, 00:00:00 UTC). - The “Blocking” Model:
time.sleep(n)pauses the entire program for seconds.- How to read: “time dot sleep of n.”
- Meaning: The program halts all execution for seconds—useful for delays, rate limiting, and pacing output. During this time, the program is “blocked” and cannot respond to user input or perform other tasks.
- Profiling: Measuring performance by subtracting a start
time.time()from an endtime.time(). - Example Usage:
import time
start_time = time.time()
# Simulate a task
print("Starting task...")
time.sleep(2)
print("Task complete.")
end_time = time.time()
duration = end_time - start_time
print(f"Total time: {duration:.2f} seconds")
- Human Readability:
time.ctime()converts a timestamp to a readable string.