Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 8 additions & 26 deletions babel/dates.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,21 +17,15 @@

from __future__ import annotations

import datetime
import math
import re
import warnings
import zoneinfo
from collections.abc import Iterable
from functools import lru_cache
from typing import TYPE_CHECKING, Literal, SupportsInt

try:
import pytz
except ModuleNotFoundError:
pytz = None
import zoneinfo

import datetime
from collections.abc import Iterable

from babel import localtime
from babel.core import Locale, default_locale, get_global
from babel.localedata import LocaleDataDict
Expand Down Expand Up @@ -225,10 +219,7 @@ def _get_time(


def get_timezone(zone: str | datetime.tzinfo | None = None) -> datetime.tzinfo:
"""Looks up a timezone by name and returns it. The timezone object
returned comes from ``pytz`` or ``zoneinfo``, whichever is available.
It corresponds to the `tzinfo` interface and can be used with all of
the functions of Babel that operate with dates.
"""Looks up a timezone by name and returns it.

If a timezone is not known a :exc:`LookupError` is raised. If `zone`
is ``None`` a local zone object is returned.
Expand All @@ -241,19 +232,10 @@ def get_timezone(zone: str | datetime.tzinfo | None = None) -> datetime.tzinfo:
if not isinstance(zone, str):
return zone

if pytz:
try:
return pytz.timezone(zone)
except pytz.UnknownTimeZoneError as e:
exc = e
else:
assert zoneinfo
try:
return zoneinfo.ZoneInfo(zone)
except zoneinfo.ZoneInfoNotFoundError as e:
exc = e

raise LookupError(f"Unknown timezone {zone}") from exc
try:
return zoneinfo.ZoneInfo(zone)
except zoneinfo.ZoneInfoNotFoundError as e:
raise LookupError(f"Unknown timezone {zone}") from e


def get_period_names(
Expand Down
43 changes: 11 additions & 32 deletions babel/localtime/_helpers.py
Original file line number Diff line number Diff line change
@@ -1,39 +1,21 @@
import zoneinfo

try:
import pytz
except ModuleNotFoundError:
pytz = None


def _get_tzinfo(tzenv: str):
"""Get the tzinfo from `zoneinfo` or `pytz`
"""Get the tzinfo from `zoneinfo`

:param tzenv: timezone in the form of Continent/City
:return: tzinfo object or None if not found
"""
if pytz:
try:
return pytz.timezone(tzenv)
except pytz.UnknownTimeZoneError:
pass
else:
try:
return zoneinfo.ZoneInfo(tzenv)
except ValueError as ve:
# This is somewhat hacky, but since _validate_tzfile_path() doesn't
# raise a specific error type, we'll need to check the message to be
# one we know to be from that function.
# If so, we pretend it meant that the TZ didn't exist, for the benefit
# of `babel.localtime` catching the `LookupError` raised by
# `_get_tzinfo_or_raise()`.
# See https://github.com/python-babel/babel/issues/1092
if str(ve).startswith("ZoneInfo keys "):
return None
except zoneinfo.ZoneInfoNotFoundError:
pass

return None
try:
return zoneinfo.ZoneInfo(tzenv)
except (zoneinfo.ZoneInfoNotFoundError, ValueError):
# ValueError is raised for malformed keys.
# If that happens, we pretend it meant that the TZ didn't exist,
# for the benefit of `babel.localtime` catching the `LookupError`
# raised by `_get_tzinfo_or_raise()`.
# See https://github.com/python-babel/babel/issues/1092
return None


def _get_tzinfo_or_raise(tzenv: str):
Expand All @@ -48,7 +30,4 @@ def _get_tzinfo_or_raise(tzenv: str):

def _get_tzinfo_from_file(tzfilename: str):
with open(tzfilename, 'rb') as tzfile:
if pytz:
return pytz.tzfile.build_tzinfo('local', tzfile)
else:
return zoneinfo.ZoneInfo.from_file(tzfile)
return zoneinfo.ZoneInfo.from_file(tzfile)
2 changes: 1 addition & 1 deletion babel/localtime/_unix.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ def _tz_from_env(tzenv: str) -> datetime.tzinfo:
def _get_localzone(_root: str = '/') -> datetime.tzinfo:
"""Tries to find the local timezone configuration.
This method prefers finding the timezone name and passing that to
zoneinfo or pytz, over passing in the localtime file, as in the later
zoneinfo, over passing in the localtime file, as in the later
case the zoneinfo name is unknown.
The parameter _root makes the function look for files like /etc/localtime
beneath the _root directory. This is primarily used by the tests.
Expand Down
9 changes: 5 additions & 4 deletions docs/dates.rst
Original file line number Diff line number Diff line change
Expand Up @@ -276,9 +276,10 @@ class, which you need appropriate implementations for to actually use in your
application. Babel includes a ``tzinfo`` implementation for UTC (Universal
Time).

Babel uses either `zoneinfo`_ or `pytz`_ for timezone support.
If pytz is installed, it is preferred over the standard library's zoneinfo.
You can directly interface with either of these modules from within Babel:
Babel uses the standard library `zoneinfo`_ module for timezone support.
Timezone objects from `pytz`_ are accepted wherever a ``tzinfo`` is required,
but Babel itself does not create them. You can directly interface with
``zoneinfo`` from within Babel:

.. code-block:: pycon

Expand Down Expand Up @@ -315,7 +316,7 @@ your operating system. It's provided through the ``LOCALTZ`` constant:

>>> from babel.dates import LOCALTZ, get_timezone_name
>>> LOCALTZ
<DstTzInfo 'Europe/Vienna' CET+1:00:00 STD>
zoneinfo.ZoneInfo(key='Europe/Vienna')
>>> get_timezone_name(LOCALTZ)
'Central European Time'

Expand Down
6 changes: 3 additions & 3 deletions docs/dev.rst
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,9 @@ Unicode is a big deal in Babel. Here is how the rules are set up:
Dates and Timezones
-------------------

Babel's timezone support relies on either ``pytz`` or ``zoneinfo``; if ``pytz``
is installed, it is preferred over ``zoneinfo``. Babel should assume that any
timezone objects can be from either of these modules.
Babel's timezone support relies on ``zoneinfo``, however callers may still pass
``pytz`` timezone objects so Babel should assume that any timezone objects can
be from either of these modules.

Assumptions to make:

Expand Down
10 changes: 3 additions & 7 deletions docs/installation.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,9 @@
Installation
============

Babel is distributed as a standard Python package fully set up with all
the dependencies it needs. On Python versions where the standard library
`zoneinfo`_ module is not available, `pytz`_ needs to be installed for
timezone support. If `pytz`_ is installed, it is preferred over the
standard library `zoneinfo`_ module where possible.

.. _pytz: https://pythonhosted.org/pytz/
Babel is distributed as a standard Python package fully set up with all the
dependencies it needs. Timezone support uses the standard library `zoneinfo`_
module which reads the system's timezone database.

.. _zoneinfo: https://docs.python.org/3/library/zoneinfo.html

Expand Down
5 changes: 5 additions & 0 deletions tests/test_dates.py
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,11 @@ def test_get_time_format():
'HH:mm:ss zzzz')


def test_get_timezone_unknown():
with pytest.raises(LookupError):
dates.get_timezone("DoesNot/Exist")


def test_get_timezone_gmt(timezone_getter):
dt = datetime(2007, 4, 1, 15, 30)
assert dates.get_timezone_gmt(dt, locale='en') == 'GMT+00:00'
Expand Down
17 changes: 2 additions & 15 deletions tests/test_localtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,27 +4,14 @@

import pytest

from babel.localtime import _helpers, get_localzone
from babel.localtime import get_localzone


@pytest.mark.skipif(
sys.platform == "win32",
reason="Issue 1092 is not applicable on Windows",
)
def test_issue_1092_without_pytz(monkeypatch):
pytest.importorskip("zoneinfo", reason="zoneinfo is not available")
monkeypatch.setenv("TZ", "/UTC") # Malformed timezone name.
# In case pytz _is_ also installed, we want to pretend it's not, so patch it out...
monkeypatch.setattr(_helpers, "pytz", None)
with pytest.raises(LookupError):
get_localzone()


@pytest.mark.skipif(
sys.platform == "win32",
reason="Issue 1092 is not applicable on Windows",
)
def test_issue_1092_with_pytz(monkeypatch):
def test_issue_1092(monkeypatch):
pytest.importorskip("pytz", reason="pytz is not installed")
monkeypatch.setenv("TZ", "/UTC") # Malformed timezone name.
with pytest.raises(LookupError):
Expand Down
Loading