Text of peps.python.org › pep-0830 as Styx crawled it on Nov 18, 2026. The page may have changed since. Only its words are kept, without pictures or layout, and only the first part of a long page.

Open the live page

PEP 830 – Add timestamps to exceptions and tracebacks | peps.python.org

PEP 830 – Add timestamps to exceptions and tracebacks PEP 830 – Add timestamps to exceptions and tracebacks Author : Gregory P. Smith <greg at krypto.org> Discussions-To : Discourse thread Status : Draft Type : Standards Track Created : 15-Mar-2026 Python-Version : 3.16 Post-History : 12-Apr-2026 , 18-Apr-2026 Table of Contents Abstract Motivation Specification Exception Timestamp Attribute Control Flow Exceptions Configuration Display Format Traceback Module Updates Doctest Updates Rationale Instantiation Time vs.

Raise Time Performance Measurements Backwards Compatibility Pickled Exception Examples Maintenance Burden Security Implications How to Teach This Reference Implementation Rejected Ideas Using Exception Notes Using sys.excepthook Using sys.monitoring Always Collecting vs. Always Displaying Runtime API Timestamp in the Traceback Header Line More Descriptive timestamps Parameter Name Custom Timestamp Formats Configurable Control Flow Exception Set Millisecond Precision Separate Millisecond and Microsecond Display Formats Returning None When Unset Using a Coarse Clock Open Issues Display Location Benchmarking the sys.monitoring Alternative Recording Time of First Raise Acknowledgements Change History Copyright Abstract This PEP adds an optional __timestamp_ns__ attribute to BaseException that records when the exception was instantiated with no observable overhead.

When enabled via environment variable or command-line flag, formatted tracebacks display this timestamp alongside the exception message. Motivation With the introduction of exception groups ( PEP 654 ), Python programs can now propagate multiple unrelated exceptions simultaneously. When debugging these, or when correlating exceptions with external logs and metrics, knowing when each exception occurred is often as important as knowing what occurred; a common pain point when diagnosing problems in production.

Currently there is no standard way to obtain this information. Python authors must manually add timing to exception messages or rely on logging frameworks, which can be costly and is inconsistently done and error-prone. Consider an async service that fetches data from multiple backends concurrently and reports every failure rather than failing fast. The resulting ExceptionGroup contains all the errors in submission order, with no indication of when each one occurred: import asyncio async def fetch_user ( uid ): await asyncio . sleep ( 0.5 ) raise ConnectionError ( f "User service timeout for { uid } " ) async def fetch_orders ( uid ): await asyncio . sleep ( 0.1 ) raise ValueError ( f "Invalid user_id format: { uid } " ) async def fetch_recommendations ( uid ): await asyncio . sleep ( 2.3 ) raise TimeoutError ( "Recommendation service timeout" ) async def get_dashboard ( uid ): results = await asyncio . gather ( fetch_user ( uid ), fetch_orders ( uid ), fetch_recommendations ( uid ), return_exceptions = True , ) errors = [ r for r in results if isinstance ( r , Exception )] if errors : raise ExceptionGroup ( "dashboard fetch failed" , errors ) asyncio . run ( get_dashboard ( "usr_12@34" )) With PYTHON_TRACEBACK_TIMESTAMPS=iso , the output becomes: + Exception Group Traceback (most recent call last): | File "service.py", line 26, in <module> | asyncio.run(get_dashboard("usr_12@34")) | ... | File "service.py", line 24, in get_dashboard | raise ExceptionGroup("dashboard fetch failed", errors) | ExceptionGroup: dashboard fetch failed (3 sub-exceptions) <@2026-04-19T07:24:31.102431Z> +-+---------------- 1 ---------------- | Traceback (most recent call last): | File "service.py", line 5, in fetch_user | raise ConnectionError(f"User service timeout for {uid}") | ConnectionError: User service timeout for usr_12@34 <@2026-04-19T07:24:29.300461Z> +---------------- 2 ---------------- | Traceback (most recent call last): | File "service.py", line 9, in fetch_orders | raise ValueError(f"Invalid user_id format: {uid}") | ValueError: Invalid user_id format: usr_12@34 <@2026-04-19T07:24:28.899918Z> +---------------- 3 ---------------- | Traceback (most recent call last): | File "service.py", line 13, in fetch_recommendations | raise TimeoutError("Recommendation service timeout") | TimeoutError: Recommendation service timeout <@2026-04-19T07:24:31.102394Z> +------------------------------------ The sub-exceptions are listed in submission order, but the timestamps reveal that the order validation actually failed first (at 28.899s), the user service half a second later (at 29.300s), and the recommendation service last after 2.3 seconds (at 31.102s).

These can also be correlated with metrics dashboards, load balancer logs, traces from other services, or the program’s own logs to build a complete picture. Specification Exception Timestamp Attribute A new read/write attribute __timestamp_ns__ is added to BaseException . It stores nanoseconds since the Unix epoch in UTC (same semantics and precision as time.time_ns() ) as a C int64_t exposed via a member descriptor.

When timestamps are disabled, for control flow exceptions (see below), or if reading the clock fails, the value is 0 . Exception instances reused from an internal free list, such as MemoryError , are timestamped when handed out rather than when originally allocated. The interpreter’s last-resort static MemoryError singleton retains a __timestamp_ns__ of 0 . Control Flow Exceptions To avoid performance impact on normal control flow, timestamps are not collected for StopIteration or StopAsyncIteration even when the feature is enabled.

These exceptions are raised at extremely high frequency during iteration; the check uses C type pointer identity (not isinstance ) for negligible overhead. Other idioms sometimes described as exceptions-as-control-flow, such as hasattr , three-argument getattr , dict.get , dict.setdefault , and __missing__ dispatch, do not need special handling: the hot paths in CPython’s C internals already return “not found” without instantiating an exception object.

Configuration The feature is enabled through CPython’s two standard mechanisms: PYTHON_TRACEBACK_TIMESTAMPS environment variable Set to ns or 1 for nanosecond-precision decimal timestamps, or iso for ISO 8601 UTC format. Empty, unset, or 0 disables timestamps (the default). -X traceback_timestamps=<format> command-line option Accepts the same values. Takes precedence over the environment variable. If -X traceback_timestamps is specified with no =<format> value, that acts as an implicit =1 (nanosecond-precision format).

Consistent with other CPython config behavior, an invalid environment variable value is silently ignored while an invalid -X flag value is an error. A new traceback_timestamps field in PyConfig stores the selected format, accessible as sys.flags.traceback_timestamps . Display Format Timestamps are appended to the exception message line in tracebacks using the format <@timestamp> . This affects formatted traceback output only; str(exc) and repr(exc) are unchanged.

Example with iso : Traceback (most recent call last): File "<stdin>" , line 3 , in california_raisin raise RuntimeError ( "not enough sunshine" ) RuntimeError : not enough sunshine <@2026-04-12T18:07:30.346914Z> When colorized output is enabled, the timestamp is rendered in a muted color to keep it visually distinct from the exception message. The ns format renders seconds since the epoch with nine fractional digits, for example <@1776017178.687320256> .

The iso format renders at microsecond resolution; the underlying __timestamp_ns__ value is always nanosecond precision regardless of the display format. Traceback Module Updates TracebackException and the public formatting functions ( print_exc , print_exception , format_exception , format_exception_only ) gain a timestamps keyword argument (default None ): None Follow the global configuration. Timestamps are shown only when the feature is enabled, using the configured format.

False Never show timestamps, even when the featu

The rest of this page is on the live site.