On this page
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
- Never measure elapsed time or timeouts with
time.time(): Wall clocks can jump forward or backward during NTP sync or DST changes; usemonotonic()orperf_counter(). - Never call
time.sleep()inside anasync defcoroutine: It blocks the entire event loop; useawait asyncio.sleep(...). time.sleep(0.01)is a lower bound, not exact: OS scheduler jitter can wake the thread slightly later.
Common Functions
- time.asctime() —
asctime([tuple]) -> string— Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'. - time.clock_getres() —
clock_getres(clk_id) -> floating-point number— Return the resolution (precision) of the specified clock clk_id. - time.clock_gettime() —
clock_gettime(clk_id, /)— Return the time of the specified clock clk_id as a float. - time.clock_gettime_ns() —
clock_gettime_ns(clk_id, /)— Return the time of the specified clock clk_id as nanoseconds (int). - time.clock_settime() —
clock_settime(clk_id, time)— Set the time of the specified clock clk_id. - time.clock_settime_ns() —
clock_settime_ns(clk_id, time)— Set the time of the specified clock clk_id with nanoseconds. - time.ctime() —
ctime(seconds) -> string— Convert a time in seconds since the Epoch to a string in local time. - time.get_clock_info() —
get_clock_info(name: str) -> dict— Get information of the specified clock. - time.gmtime() —
gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,— tm_sec, tm_wday, tm_yday, tm_isdst) Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a. - time.localtime() —
localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,— tm_sec,tm_wday,tm_yday,tm_isdst) Convert seconds since the Epoch to a time tuple expressing local time. - time.mktime() —
mktime(object, /)— Convert a time tuple in local time to seconds since the Epoch. - time.monotonic() —
monotonic()— Monotonic clock, cannot go backward. - time.monotonic_ns() —
monotonic_ns()— Monotonic clock, cannot go backward, as nanoseconds. - time.perf_counter() —
perf_counter()— Performance counter for benchmarking. - time.perf_counter_ns() —
perf_counter_ns()— Performance counter for benchmarking as nanoseconds. - time.process_time() —
process_time()— Process time for profiling: sum of the kernel and user-space CPU time. - time.process_time_ns() —
process_time_ns()— Process time for profiling as nanoseconds: sum of the kernel and user-space CPU time. - time.sleep() —
sleep(object, /)— Delay execution for a given number of seconds. The argument may be a floating-point number for subsecond precision. - time.strftime() —
strftime(format[, tuple]) -> string— Convert a time tuple to a string according to a format specification. - time.strptime() —
strptime(string, format) -> struct_time— Parse a string to a time tuple according to a format specification. - time.thread_time() —
thread_time()— Thread time for profiling: sum of the kernel and user-space CPU time. - time.thread_time_ns() —
thread_time_ns()— Thread time for profiling as nanoseconds: sum of the kernel and user-space CPU time. - time.time() —
time()— Return the current time in seconds since the Epoch. - time.time_ns() —
time_ns()— Return the current time in nanoseconds since the Epoch. - time.tzset() —
tzset()— Initialize, or reinitialize, the local timezone to the value stored in os.environ['TZ']. The TZ environment variable should be specified in standard Unix timezone format as documented in the tzset man page
Classes & Objects
- time.struct_time — The time value as returned by gmtime(), localtime(), and strptime(), and accepted by asctime(), mktime() and strftime(). May be considered as a sequence of 9 integers. (Methods:
.count(),.index())
Constants & Attributes
time.CLOCK_MONOTONIC(int) =6time.CLOCK_MONOTONIC_RAW(int) =4time.CLOCK_MONOTONIC_RAW_APPROX(int) =5time.CLOCK_PROCESS_CPUTIME_ID(int) =12time.CLOCK_REALTIME(int) =0time.CLOCK_THREAD_CPUTIME_ID(int) =16time.CLOCK_UPTIME_RAW(int) =8time.CLOCK_UPTIME_RAW_APPROX(int) =9time.altzone(int) =25200time.daylight(int) =1time.timezone(int) =28800time.tzname(tuple) =('PST', 'PDT')
Linked from
- tuts/python3
- tuts/python3/stdlib_module
- tuts/python3/stdlib_module/argparse
- tuts/python3/stdlib_module/asyncio
- tuts/python3/stdlib_module/concurrent
- tuts/python3/stdlib_module/contextvars
- tuts/python3/stdlib_module/ctypes
- tuts/python3/stdlib_module/curses
- tuts/python3/stdlib_module/datetime
- tuts/python3/stdlib_module/errno
- tuts/python3/stdlib_module/fcntl
- tuts/python3/stdlib_module/filecmp
- tuts/python3/stdlib_module/fileinput
- tuts/python3/stdlib_module/fnmatch
- tuts/python3/stdlib_module/genericpath
- tuts/python3/stdlib_module/getopt
- tuts/python3/stdlib_module/getpass
- tuts/python3/stdlib_module/glob
- tuts/python3/stdlib_module/grp
- tuts/python3/stdlib_module/io
- tuts/python3/stdlib_module/linecache
- tuts/python3/stdlib_module/logging
- tuts/python3/stdlib_module/mmap
- tuts/python3/stdlib_module/msvcrt
- tuts/python3/stdlib_module/multiprocessing
- tuts/python3/stdlib_module/nt
- tuts/python3/stdlib_module/ntpath
- tuts/python3/stdlib_module/optparse
- tuts/python3/stdlib_module/os
- tuts/python3/stdlib_module/pathlib
- tuts/python3/stdlib_module/platform
- tuts/python3/stdlib_module/posix
- tuts/python3/stdlib_module/posixpath
- tuts/python3/stdlib_module/pty
- tuts/python3/stdlib_module/pwd
- tuts/python3/stdlib_module/queue
- tuts/python3/stdlib_module/resource
- tuts/python3/stdlib_module/sched
- tuts/python3/stdlib_module/select
- tuts/python3/stdlib_module/selectors
- tuts/python3/stdlib_module/shutil
- tuts/python3/stdlib_module/signal
- tuts/python3/stdlib_module/socket
- tuts/python3/stdlib_module/ssl
- tuts/python3/stdlib_module/stat
- tuts/python3/stdlib_module/stdlib_module
- tuts/python3/stdlib_module/subprocess
- tuts/python3/stdlib_module/syslog
- tuts/python3/stdlib_module/tempfile
- tuts/python3/stdlib_module/termios
- tuts/python3/stdlib_module/threading
- tuts/python3/stdlib_module/timeit
- tuts/python3/stdlib_module/tty
- tuts/python3/stdlib_module/winreg
- tuts/python3/stdlib_module/winsound
Related notes
- tuts/python3/stdlib_module/datetime Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/fileinput Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/io Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/os Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/pathlib Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/stat Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/stdlib_module Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/threading Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/timeit Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module links to this page; shared tags: #stdlib