On this page
  1. time
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Enforcing a Monotonic Deadline Loop
  7. 2. Nanosecond Integer Precision (perf_counter_ns, time_ns)
  8. Gotchas & Boundaries
  9. Common Functions
  10. Classes & Objects
  11. Constants & Attributes

time

Prev: threading | Up: stdlib_module | Next: timeit
Rel: pathlib, os, io, fileinput, stat
Ref: docs.python.org — time
Tags: #public #python3 #stdlib


Import

import time

Overview

Low-level OS clock access (monotonic, perf_counter, time, process_time, sleep) and C-style time formatting. Use time.monotonic() for timeouts/deadlines and time.perf_counter() for benchmarking elapsed duration; use datetime + zoneinfo for calendar dates, timezones, and ISO 8601 timestamps.

Quick Start

import time

start = time.perf_counter()
time.sleep(0.01)
elapsed_ms = (time.perf_counter() - start) * 1000
assert elapsed_ms >= 9.0

Implementation Walkthrough

1. Enforcing a Monotonic Deadline Loop

Always compute deadlines with time.monotonic() (which never jumps backward on NTP or DST adjustments):

import time

def wait_until(predicate, *, timeout: float = 1.0, interval: float = 0.02) -> bool:
    deadline = time.monotonic() + timeout
    while time.monotonic() < deadline:
        if predicate():
            return True
        remaining = deadline - time.monotonic()
        if remaining > 0:
            time.sleep(min(interval, remaining))
    return predicate()

assert wait_until(lambda: True, timeout=0.1)

2. Nanosecond Integer Precision (perf_counter_ns, time_ns)

import time

t0 = time.perf_counter_ns()
_ = sum(range(1000))
elapsed_ns = time.perf_counter_ns() - t0
assert elapsed_ns >= 0

Gotchas & Boundaries

Common Functions

Classes & Objects

Constants & Attributes

Linked from

Related notes