Skip to content

Commit 333cab0

Browse files
[3.14] gh-137754: Fix import of zoneinfo if _datetime is not available (GH-137845) (GH-138084)
Both modules should use the Python implementation in that case. (cherry picked from commit 6620ef0) Co-authored-by: Serhiy Storchaka <[email protected]>
1 parent 0188e0f commit 333cab0

File tree

3 files changed

+27
-1
lines changed

3 files changed

+27
-1
lines changed

Lib/test/test_zoneinfo/test_zoneinfo.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
from test.test_zoneinfo import _support as test_support
2323
from test.test_zoneinfo._support import TZPATH_TEST_LOCK, ZoneInfoTestBase
2424
from test.support.import_helper import import_module, CleanImport
25+
from test.support.script_helper import assert_python_ok
2526

2627
lzma = import_module('lzma')
2728
py_zoneinfo, c_zoneinfo = test_support.get_modules()
@@ -1955,6 +1956,26 @@ class CTestModule(TestModule):
19551956
module = c_zoneinfo
19561957

19571958

1959+
class MiscTests(unittest.TestCase):
1960+
def test_pydatetime(self):
1961+
# Test that zoneinfo works if the C implementation of datetime
1962+
# is not available and the Python implementation of datetime is used.
1963+
# The Python implementation of zoneinfo should be used in thet case.
1964+
#
1965+
# Run the test in a subprocess, as importing _zoneinfo with
1966+
# _datettime disabled causes crash in the previously imported
1967+
# _zoneinfo.
1968+
assert_python_ok('-c', '''if 1:
1969+
import sys
1970+
sys.modules['_datetime'] = None
1971+
import datetime
1972+
import zoneinfo
1973+
tzinfo = zoneinfo.ZoneInfo('Europe/London')
1974+
datetime.datetime(2025, 10, 26, 2, 0, tzinfo=tzinfo)
1975+
''',
1976+
PYTHONTZPATH=str(ZONEINFO_DATA.tzpath))
1977+
1978+
19581979
class ExtensionBuiltTest(unittest.TestCase):
19591980
"""Smoke test to ensure that the C and Python extensions are both tested.
19601981

Lib/zoneinfo/__init__.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,10 @@
1212

1313
try:
1414
from _zoneinfo import ZoneInfo
15-
except ImportError: # pragma: nocover
15+
except (ImportError, AttributeError): # pragma: nocover
16+
# AttributeError: module 'datetime' has no attribute 'datetime_CAPI'.
17+
# This happens when the '_datetime' module is not available and the
18+
# pure Python implementation is used instead.
1619
from ._zoneinfo import ZoneInfo
1720

1821
reset_tzpath = _tzpath.reset_tzpath
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix import of the :mod:`zoneinfo` module if the C implementation of the
2+
:mod:`datetime` module is not available.

0 commit comments

Comments
 (0)