Wall-clock timestamps
Record event timestamps or generate epoch-based identifiers.
Python · Module
Python’s time module provides clocks, sleeping, epoch-based conversions, and formatting utilities. Use wall-clock functions for timestamps and monotonic or performance counters for measuring elapsed durations.
The time module exposes clocks, sleeping, epoch conversions, formatting, and platform-related timing information. Use wall-clock functions for timestamps and monotonic performance counters for measuring durations.
import time
time.time()
time.time_ns()
time.sleep(secs)
time.gmtime([secs])
time.localtime([secs])
time.strftime(format[, t])
time.strptime(string[, format])| Name | Type | Description |
|---|---|---|
format | str | Format string containing directives that control the resulting textual representation. |
secs | float | None | Optional epoch timestamp; when omitted, the current time is used. |
The module provides clock values, epoch conversions, formatted strings, parsed struct_time values, and sleep operations; exact return types depend on the selected function.
import time
started = time.perf_counter()
time.sleep(0.01)
elapsed = time.perf_counter() - started
print(f"Elapsed: {elapsed:.3f}s")Measures elapsed duration with a monotonic performance counter and pauses briefly.
Record event timestamps or generate epoch-based identifiers.
Measure request, job, or function duration without being affected by wall-clock corrections.
Pause between polling attempts or implement simple retry delays.
Convert epoch values into UTC or local calendar fields and format them for output.
time.time() returns the current wall-clock time as seconds since the epoch, represented as a floating-point number. It is appropriate for timestamps, but wall-clock adjustments can affect elapsed-time calculations.
Follow-up: Which clock should measure a duration? Use time.monotonic() or time.perf_counter(), because these clocks are intended for elapsed-time measurement rather than civil timestamps.
time.sleep() suspends execution for at least the requested interval, although scheduling and system activity can make the actual delay longer. It is useful for pauses and retry backoff.
Follow-up: How should a precise short duration be measured? Record time.perf_counter() before and after the operation and subtract the readings.
gmtime() converts epoch seconds to a UTC struct_time, while localtime() converts them to local time. struct_time exposes calendar fields through both indexes and named attributes.
Follow-up: How can a struct_time become epoch seconds? Use calendar.timegm() for UTC or mktime() for local time.
datetimecalendartime.timetime.time_nstime.monotonictime.perf_countertime.sleeptime.gmtime