This commit is contained in:
Iliyan Angelov
2025-09-19 11:58:53 +03:00
parent 306b20e24a
commit 6b247e5b9f
11423 changed files with 1500615 additions and 778 deletions

View File

@@ -0,0 +1,25 @@
from django import VERSION, conf
from .base import TimeZoneNotFoundError
USE_PYTZ_DEFAULT = getattr(conf.settings, "USE_DEPRECATED_PYTZ", VERSION < (4, 0))
tz_backend_cache = {}
def get_tz_backend(use_pytz):
use_pytz = USE_PYTZ_DEFAULT if use_pytz is None else use_pytz
if use_pytz not in tz_backend_cache:
if use_pytz:
from .pytz import PYTZBackend
klass = PYTZBackend
else:
from .zoneinfo import ZoneInfoBackend
klass = ZoneInfoBackend
tz_backend_cache[use_pytz] = klass()
return tz_backend_cache[use_pytz]
__all__ = ["TimeZoneNotFoundError", "get_tz_backend"]

View File

@@ -0,0 +1,19 @@
from abc import ABC, abstractmethod
class TimeZoneNotFoundError(Exception):
pass
class TimeZoneBackend(ABC):
utc_tzobj = None
all_tzstrs = None
base_tzstrs = None
@abstractmethod
def is_tzobj(self, value):
pass
@abstractmethod
def to_tzobj(self, tzstr):
pass

View File

@@ -0,0 +1,18 @@
import pytz
from .base import TimeZoneBackend, TimeZoneNotFoundError
class PYTZBackend(TimeZoneBackend):
utc_tzobj = pytz.utc
all_tzstrs = pytz.all_timezones
base_tzstrs = pytz.common_timezones
def is_tzobj(self, value):
return value is pytz.UTC or isinstance(value, pytz.tzinfo.BaseTzInfo)
def to_tzobj(self, tzstr):
try:
return pytz.timezone(tzstr)
except pytz.UnknownTimeZoneError as err:
raise TimeZoneNotFoundError from err

View File

@@ -0,0 +1,27 @@
try:
import zoneinfo
except ImportError:
from backports import zoneinfo
from .base import TimeZoneBackend, TimeZoneNotFoundError
class ZoneInfoBackend(TimeZoneBackend):
utc_tzobj = zoneinfo.ZoneInfo("UTC")
all_tzstrs = zoneinfo.available_timezones()
base_tzstrs = zoneinfo.available_timezones()
# Remove the "Factory" timezone as it can cause ValueError exceptions on
# some systems, e.g. FreeBSD, if the system zoneinfo database is used.
all_tzstrs.discard("Factory")
base_tzstrs.discard("Factory")
def is_tzobj(self, value):
return isinstance(value, zoneinfo.ZoneInfo)
def to_tzobj(self, tzstr):
if tzstr in (None, ""):
raise TimeZoneNotFoundError
try:
return zoneinfo.ZoneInfo(tzstr)
except zoneinfo.ZoneInfoNotFoundError as err:
raise TimeZoneNotFoundError from err