Uptime Library
The `uptime` library provides a cross-platform way to retrieve system uptime and boot time, aiming to do so without relying on external processes like parsing `uptime(1)` command output. It works on various major platforms, including Linux, Windows, macOS, and BSD systems. Despite its current version 3.0.1 being released in 2013, it remains a stable and widely used utility for basic system information.
Common errors
-
ModuleNotFoundError: No module named 'uptime'
cause The `uptime` package is not installed in the current Python environment.fixInstall the package using pip: `pip install uptime`. -
RuntimeError: The datetime module isn't available
cause The standard `datetime` module, which is a dependency for `uptime.boottime()`, is missing or inaccessible in the Python environment. This is highly unusual for a standard library module.fixThis indicates a potentially corrupted or non-standard Python installation. Verify the integrity of your Python installation and ensure the `datetime` module is present and importable. Reinstalling Python might be necessary.
Warnings
- gotcha The `uptime` library heavily relies on Python's standard `ctypes` module for platform-specific system calls. On less common or custom Python installations, a broken or misconfigured `ctypes` can result in incorrect uptime values or `None` being returned.
- gotcha `uptime.uptime()` returns the system's uptime as a `float` representing seconds, while `uptime.boottime()` returns the boot time as a `datetime.datetime` object. These different return types should be handled appropriately in arithmetic or display operations.
Install
-
pip install uptime
Imports
- uptime
from uptime import uptime
- boottime
from uptime import boottime
Quickstart
from uptime import uptime, boottime
import datetime
def run_quickstart():
try:
system_uptime_seconds = uptime()
if system_uptime_seconds is not None:
print(f"System Uptime: {system_uptime_seconds:.2f} seconds")
uptime_timedelta = datetime.timedelta(seconds=system_uptime_seconds)
print(f"System Uptime (formatted): {uptime_timedelta}")
else:
print("Could not determine system uptime.")
system_boot_time = boottime()
if system_boot_time is not None:
print(f"System Boot Time: {system_boot_time}")
else:
print("Could not determine system boot time.")
except RuntimeError as e:
print(f"An error occurred: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")
if __name__ == '__main__':
run_quickstart()