{"record":{"id":"9472d2a7a066e767","repo":"PyO3/pyo3","slug":"failed-to-import-datetime-c-api","errorCode":null,"errorMessage":"failed to import `datetime` C API","messagePattern":"failed to import `datetime` C API","errorType":"panic","errorClass":null,"httpStatus":null,"severity":"critical","filePath":"src/types/datetime.rs","lineNumber":50,"sourceCode":"#[cfg(not(Py_LIMITED_API))]\nuse core::ffi::c_int;\n\n#[cfg(not(Py_LIMITED_API))]\nfn ensure_datetime_api(py: Python<'_>) -> PyResult<&'static PyDateTime_CAPI> {\n    if let Some(api) = unsafe { pyo3_ffi::PyDateTimeAPI().as_ref() } {\n        Ok(api)\n    } else {\n        unsafe {\n            PyDateTime_IMPORT();\n            pyo3_ffi::PyDateTimeAPI().as_ref()\n        }\n        .ok_or_else(|| PyErr::fetch(py))\n    }\n}\n\n#[cfg(not(Py_LIMITED_API))]\nfn expect_datetime_api(py: Python<'_>) -> &'static PyDateTime_CAPI {\n    ensure_datetime_api(py).expect(\"failed to import `datetime` C API\")\n}\n\n// Type Check macros\n//\n// These are bindings around the C API typecheck macros, all of them return\n// `1` if True and `0` if False. In all type check macros, the argument (`op`)\n// must not be `NULL`. The implementations here all call ensure_datetime_api\n// to ensure that the PyDateTimeAPI is initialized before use\n//\n//\n// # Safety\n//\n// These functions must only be called when the GIL is held!\n#[cfg(not(Py_LIMITED_API))]\nmacro_rules! ffi_fun_with_autoinit {\n    ($(#[$outer:meta] unsafe fn $name: ident($arg: ident: *mut PyObject) -> $ret: ty;)*) => {\n        $(\n            #[$outer]","sourceCodeStart":32,"sourceCodeEnd":68,"githubUrl":"https://github.com/PyO3/pyo3/blob/ac9b6899d348be4d54614d060dea53a645a12e36/src/types/datetime.rs#L32-L68","documentation":"PyO3's `datetime` support caches a pointer to the CPython `PyDateTime_CAPI` structure obtained via `PyDateTime_IMPORT`. `expect_datetime_api` panics if `ensure_datetime_api` returns `Err` — i.e. importing the `datetime` C API failed (typically because the `datetime` module could not be imported). The panic propagates the fetched `PyErr`'s absence as a Rust panic instead of a Python exception.","triggerScenarios":"Extracting to `chrono`/`time` datetime types or constructing `PyDateTime`/`PyDate`/`PyTime`/`PyDelta` objects when the `datetime` module is unavailable; frozen/PyOxidizer/PyInstaller builds missing `datetime`; a broken `sys.path` hiding the stdlib.","commonSituations":"Frozen binaries (PyInstaller, PyOxidizer, embedded Python) that stripped `datetime`; stub-based or partial Python distributions; calling datetime-related Rust APIs at interpreter shutdown.","solutions":["Ensure the Python runtime's stdlib (especially `datetime`) is importable: check `sys.path` and that `datetime.py`/`_datetime` module is included in frozen builds","Add a hidden import of `datetime` in PyInstaller/PyOxidizer configs (`--hidden-import datetime`)","Verify the interpreter is fully initialized before calling datetime APIs (not during `Py_Finalize`)","Use `ensure_datetime_api` directly and handle the returned `PyErr` instead of the panicking helper"],"exampleFix":"// PyInstaller spec\n// before\n# no hidden import, stdlib pruned\n// after\nhiddenimports=['datetime']","handlingStrategy":"validation","validationCode":"# Python: verify datetime C API availability before calling datetime-dependent Rust code\nimport datetime  # raises ImportError early if stdlib is pruned\nassert hasattr(datetime, 'date')","typeGuard":"def datetime_api_available() -> bool:\n    try:\n        import datetime\n        return True\n    except ImportError:\n        return False","tryCatchPattern":"try:\n    result = rust_parse_datetime(value)\nexcept ImportError:\n    result = fallback_python_parsing(value)","preventionTips":["Include 'datetime' as a hidden import in PyInstaller/PyOxidizer builds","Test frozen binaries for stdlib completeness","Never call datetime-dependent APIs during interpreter finalization","Keep sys.path pointing at a complete stdlib"],"tags":["rust","pyo3","datetime","c-api","frozen-binary"],"backgroundTag":"datetime-capi-import-failed","analyzedSha":"ac9b6899d348be4d54614d060dea53a645a12e36","analyzedAt":"2026-09-05T09:20:35.319Z","contentChangedAt":"2026-09-05T09:20:35.319Z","schemaVersion":2},"datasetVersion":"2026-09-12T12:17:11.808Z"}