Learn the differences between wall clocks, monotonic clocks, and sleep.
How It Works
The time module provides epoch timestamps, elapsed-time counters, and operating-system time conversions. Use monotonic() for deadlines and perf_counter() for durations; system wall time may jump when adjusted.
Step-by-Step Example
import time
first_tick = time.monotonic()
second_tick = time.monotonic()
print(second_tick >= first_tick)
print(isinstance(time.time(), float))
Understanding the Example
- The expression 'time.monotonic()' supplies the value stored as 'first_tick'. This value is then used or checked by the later statements.
- The expression 'time.monotonic()' supplies the value stored as 'second_tick'. This value is then used or checked by the later statements.
Run the complete example as written, then inspect the displayed result. The values returned by the operation are more important than simply seeing the script finish.
Where This Fits in a Real Program
For event timestamps, distinguish the displayed local clock from the instant that it represents. Store or exchange an unambiguous aware value, then convert it when displaying it to a user. For repeated calendar appointments, use a geographic timezone so daylight-saving rules are not lost.
Practice: Try It Yourself
Use datetime for human-readable calendars and time for low-level clocks.
For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.
Further Reading
Read the official Python documentation for complete parameters, return types and exceptions.
Common Beginner Mistakes
- Using time.time() for reliable elapsed-time measurements when the system clock can change.
- Measure a short loop using perf_counter() and compare it with wall-clock timestamps.
Key Takeaways
- Learn the differences between wall clocks, monotonic clocks, and sleep.
- The time module provides epoch timestamps, elapsed-time counters, and operating-system time conversions.
- Apply the demonstrated operation to the practice input and verify its result before depending on it in a larger program.