Time#
datetime, timedelta, time.monotonic, strftime.
Parsing, formatting, deadlines, and the elapsed-time recipe the
operator uses to bound a slow operation.
Current UTC datetime, timezone-aware.
from datetime import datetime, timezone
now = datetime.now(timezone.utc)
Current local datetime.
now = datetime.now()
ISO-8601 round-trip.
s = now.isoformat()
t = datetime.fromisoformat(s)
Parse a formatted timestamp.
t = datetime.strptime("2026-05-19 14:35", "%Y-%m-%d %H:%M")
Format a timestamp.
s = now.strftime("%Y-%m-%dT%H:%M:%S%z")
Add a duration to a datetime.
from datetime import timedelta
later = now + timedelta(minutes=15)
Compute elapsed wall-clock time around a block.
import time
t0 = time.perf_counter()
work()
elapsed = time.perf_counter() - t0
Monotonic-clock deadline check.
deadline = time.monotonic() + 30
while time.monotonic() < deadline:
if ready():
break
time.sleep(0.5)
Unix epoch seconds from a datetime.
epoch = int(now.timestamp())
Datetime from epoch seconds.
t = datetime.fromtimestamp(1_716_134_400, tz=timezone.utc)
Sleep for a fixed duration.
time.sleep(0.25)
References#
Snippets for the snippets catalogue.