Skip to content

Commit b9179c3

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

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
@@ -21,6 +21,7 @@
2121
from test.test_zoneinfo import _support as test_support
2222
from test.test_zoneinfo._support import OS_ENV_LOCK, TZPATH_TEST_LOCK, ZoneInfoTestBase
2323
from test.support.import_helper import import_module, CleanImport
24+
from test.support.script_helper import assert_python_ok
2425

2526
lzma = import_module('lzma')
2627
py_zoneinfo, c_zoneinfo = test_support.get_modules()
@@ -1960,6 +1961,26 @@ class CTestModule(TestModule):
19601961
module = c_zoneinfo
19611962

19621963

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

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)