A Simple Python Stopwatch
stopwatch-py is a lightweight Python library providing a simple stopwatch functionality to measure elapsed time. It is currently at version 2.0.1 and has a low release cadence, primarily focusing on minor improvements and maintenance.
Common errors
-
AttributeError: 'NoneType' object has no attribute 'duration'
cause Attempting to chain methods like `s.stop().duration` after upgrading to v2.0.0+. Methods `start()`, `stop()`, `reset()`, `restart()` no longer return `self`.fixSeparate the method calls: `s.stop(); print(s.duration)`. -
SyntaxError: invalid syntax (often pointing to type hints) or ModuleNotFoundError: No module named 'stopwatch'
cause Running `stopwatch-py` v2.0.0+ on Python versions older than 3.5, which do not support the introduced type hints.fixUpgrade your Python interpreter to version 3.5 or newer, or downgrade the library to `pip install stopwatch-py==1.x`. -
ImportError: cannot import name 'Stopwatch' from 'stopwatch.stopwatch' (.../stopwatch/stopwatch.py)
cause Attempting to import `Stopwatch` from a submodule path (`stopwatch.stopwatch`) which was used in earlier versions. As of v2.0.1, it's a single-file module.fixUpdate your import statement to `from stopwatch import Stopwatch`.
Warnings
- breaking Methods `start()`, `stop()`, `reset()`, `restart()` no longer return `self`. This change in v2.0.0 breaks method chaining.
- breaking The minimum required Python version increased from Python 3.0 to Python 3.5 due to the introduction of type hints in v2.0.0.
- gotcha The internal `__github__` constant was removed in v2.0.1. While this was not intended to break user code, any specific reliance on this internal constant will now fail.
Install
-
pip install stopwatch-py
Imports
- Stopwatch
from stopwatch.stopwatch import Stopwatch
from stopwatch import Stopwatch
Quickstart
from stopwatch import Stopwatch
import time
s = Stopwatch() # Starts automatically on creation
print(f"Stopwatch started. Elapsed: {s.duration:.2f}s")
time.sleep(1.5)
print(f"After 1.5s, Elapsed: {s.duration:.2f}s")
s.stop()
print(f"Stopwatch stopped. Elapsed: {s.duration:.2f}s")
time.sleep(0.5)
print(f"After 0.5s while stopped, Elapsed: {s.duration:.2f}s (should be same)")
s.start() # Resume
time.sleep(0.75)
print(f"After resuming for 0.75s, Total Elapsed: {s.duration:.2f}s")
s.reset() # Reset to 0 and stop
print(f"Stopwatch reset. Elapsed: {s.duration:.2f}s")