Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/pytzdata/__init__.py: 23%
56 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-07 06:35 +0000
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-07 06:35 +0000
1# -*- coding: utf-8 -*-
3import os
5from .exceptions import TimezoneNotFound
6from ._timezones import timezones
7from ._compat import FileNotFoundError
10DEFAULT_DIRECTORY = os.path.join(
11 os.path.dirname(__file__),
12 'zoneinfo'
13)
15_DIRECTORY = os.getenv('PYTZDATA_TZDATADIR', DEFAULT_DIRECTORY)
17_TIMEZONES = {}
19INVALID_ZONES = ['Factory', 'leapseconds', 'localtime', 'posixrules']
22def tz_file(name):
23 """
24 Open a timezone file from the zoneinfo subdir for reading.
26 :param name: The name of the timezone.
27 :type name: str
29 :rtype: file
30 """
31 try:
32 filepath = tz_path(name)
34 return open(filepath, 'rb')
35 except TimezoneNotFound:
36 # http://bugs.launchpad.net/bugs/383171 - we avoid using this
37 # unless absolutely necessary to help when a broken version of
38 # pkg_resources is installed.
39 try:
40 from pkg_resources import resource_stream
41 except ImportError:
42 resource_stream = None
44 if resource_stream is not None:
45 try:
46 return resource_stream(__name__, 'zoneinfo/' + name)
47 except FileNotFoundError:
48 return tz_path(name)
50 raise
53def tz_path(name):
54 """
55 Return the path to a timezone file.
57 :param name: The name of the timezone.
58 :type name: str
60 :rtype: str
61 """
62 if not name:
63 raise ValueError('Invalid timezone')
65 name_parts = name.lstrip('/').split('/')
67 for part in name_parts:
68 if part == os.path.pardir or os.path.sep in part:
69 raise ValueError('Bad path segment: %r' % part)
71 filepath = os.path.join(_DIRECTORY, *name_parts)
73 if not os.path.exists(filepath):
74 raise TimezoneNotFound('Timezone {} not found at {}'.format(name, filepath))
76 return filepath
79def set_directory(directory=None):
80 global _DIRECTORY
82 if directory is None:
83 directory = os.getenv('PYTZDATA_TZDATADIR', DEFAULT_DIRECTORY)
85 _DIRECTORY = directory
88def get_timezones():
89 """
90 Get the supported timezones.
92 The list will be cached unless you set the "fresh" attribute to True.
94 :param fresh: Whether to get a fresh list or not
95 :type fresh: bool
97 :rtype: tuple
98 """
99 base_dir = _DIRECTORY
100 zones = ()
102 for root, dirs, files in os.walk(base_dir):
103 for basename in files:
104 zone = os.path.join(root, basename)
105 if os.path.isdir(zone):
106 continue
108 zone = os.path.relpath(zone, base_dir)
110 with open(os.path.join(root, basename), 'rb') as fd:
111 if fd.read(4) == b'TZif' and zone not in INVALID_ZONES:
112 zones = zones + (zone,)
114 return tuple(sorted(zones))
117def _get_suffix(name):
118 i = name.rfind('.')
119 if 0 < i < len(name) - 1:
120 return name[i:]
121 else:
122 return ''