Skip to content

Commit 6620ef0

Browse files
gh-137754: Fix import of zoneinfo if _datetime is not available (GH-137845)
Both modules should use the Python implementation in that case.
1 parent 282e885 commit 6620ef0

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()
@@ -1946,6 +1947,26 @@ class CTestModule(TestModule):
19461947
module = c_zoneinfo
19471948

19481949

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

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)