Introduction
The time module provides time-related functions for performance measurement and scheduling.
Basic Time
import time
# Current time
time.time() # Unix timestamp
time.ctime() # Human-readable string
# Sleep
time.sleep(1) # Sleep for 1 second
# Performance measurement
start = time.time()
# ... code ...
end = time.time()
print(f"Elapsed: {end - start}")
Process Time
import time
# CPU time (not including sleep)
start_cpu = time.process_time()
# ... code ...
end_cpu = time.process_time()
# High resolution
time.perf_counter() # Most precise for measuring intervals
time.monotonic() # Never goes backward
Struct Time
import time
now = time.localtime()
print(now.tm_year, now.tm_mon, now.tm_mday)
print(now.tm_hour, now.tm_min, now.tm_sec)
# Format time
formatted = time.strftime("%Y-%m-%d %H:%M:%S", now)
# Parse time
parsed = time.strptime("2024-06-15", "%Y-%m-%d")
Practice Problems
- Measure function execution time
- Create performance benchmark
- Format timestamps for display
- Parse various date formats
- Implement retry with exponential backoff