10-16-2026, 02:40 PM
Two different questions need different clocks: "When did this event happen?" and "How long did this operation take?"
For an event timestamp, create an aware UTC datetime. This single-line example prints an ISO 8601 value containing an explicit +00:00 offset:
For an elapsed duration, use a performance counter and subtract two readings. This is a separate single-line example:
The result is a duration in seconds. The absolute counter value is not a calendar timestamp. A wall clock can be adjusted, so subtracting wall-clock timestamps is a poor choice for benchmarking or local timeouts.
Keep an explicit offset when storing an instant and convert it for display when needed. Be careful with naive datetimes: labeling a local value as UTC with replace(tzinfo=...) does not convert the instant. Use astimezone(...) on a correctly interpreted aware value for conversion.
Official references: https://docs.python.org/3/library/datetime.html and https://docs.python.org/3/library/time.h...rf_counter
For an event timestamp, create an aware UTC datetime. This single-line example prints an ISO 8601 value containing an explicit +00:00 offset:
from datetime import datetime, timezone; stamp = datetime.now(timezone.utc); print(stamp.isoformat())For an elapsed duration, use a performance counter and subtract two readings. This is a separate single-line example:
import time; start = time.perf_counter(); total = sum(range(100000)); elapsed = time.perf_counter() - start; print(elapsed)The result is a duration in seconds. The absolute counter value is not a calendar timestamp. A wall clock can be adjusted, so subtracting wall-clock timestamps is a poor choice for benchmarking or local timeouts.
Keep an explicit offset when storing an instant and convert it for display when needed. Be careful with naive datetimes: labeling a local value as UTC with replace(tzinfo=...) does not convert the instant. Use astimezone(...) on a correctly interpreted aware value for conversion.
Official references: https://docs.python.org/3/library/datetime.html and https://docs.python.org/3/library/time.h...rf_counter
