1import zoneinfo
2
3try:
4 import pytz
5except ModuleNotFoundError:
6 pytz = None
7
8
9def _get_tzinfo(tzenv: str):
10 """Get the tzinfo from `zoneinfo` or `pytz`
11
12 :param tzenv: timezone in the form of Continent/City
13 :return: tzinfo object or None if not found
14 """
15 if pytz:
16 try:
17 return pytz.timezone(tzenv)
18 except pytz.UnknownTimeZoneError:
19 pass
20 else:
21 try:
22 return zoneinfo.ZoneInfo(tzenv)
23 except ValueError as ve:
24 # This is somewhat hacky, but since _validate_tzfile_path() doesn't
25 # raise a specific error type, we'll need to check the message to be
26 # one we know to be from that function.
27 # If so, we pretend it meant that the TZ didn't exist, for the benefit
28 # of `babel.localtime` catching the `LookupError` raised by
29 # `_get_tzinfo_or_raise()`.
30 # See https://github.com/python-babel/babel/issues/1092
31 if str(ve).startswith("ZoneInfo keys "):
32 return None
33 except zoneinfo.ZoneInfoNotFoundError:
34 pass
35
36 return None
37
38
39def _get_tzinfo_or_raise(tzenv: str):
40 tzinfo = _get_tzinfo(tzenv)
41 if tzinfo is None:
42 raise LookupError(
43 f"Can not find timezone {tzenv}. \n"
44 "Timezone names are generally in the form `Continent/City`.",
45 )
46 return tzinfo
47
48
49def _get_tzinfo_from_file(tzfilename: str):
50 with open(tzfilename, 'rb') as tzfile:
51 if pytz:
52 return pytz.tzfile.build_tzinfo('local', tzfile)
53 else:
54 return zoneinfo.ZoneInfo.from_file(tzfile)