Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/dateutil/tz/win.py: 4%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1"""
2This module provides an interface to the native time zone data on Windows,
3including :py:class:`datetime.tzinfo` implementations.
5Attempting to import this module on a non-Windows platform will raise an
6:py:obj:`ImportError`.
7"""
9# This code was originally contributed by Jeffrey Harris.
10import ctypes
11import datetime
12import os
13import struct
14import winreg
15from ctypes import wintypes
17from ._common import tzrangebase
19__all__ = ["tzwin", "tzwinlocal", "tzres"]
21ONEWEEK = datetime.timedelta(7)
23TZKEYNAMENT = r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones"
24TZKEYNAME9X = r"SOFTWARE\Microsoft\Windows\CurrentVersion\Time Zones"
25TZLOCALKEYNAME = r"SYSTEM\CurrentControlSet\Control\TimeZoneInformation"
28def _settzkeyname():
29 handle = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)
30 try:
31 winreg.OpenKey(handle, TZKEYNAMENT).Close()
32 TZKEYNAME = TZKEYNAMENT
33 except OSError:
34 TZKEYNAME = TZKEYNAME9X
35 handle.Close()
36 return TZKEYNAME
39TZKEYNAME = _settzkeyname()
42class tzres:
43 """
44 Class for accessing ``tzres.dll``, which contains timezone name related
45 resources.
47 .. versionadded:: 2.5.0
48 """
49 p_wchar = ctypes.POINTER(wintypes.WCHAR) # Pointer to a wide char
51 def __init__(self, tzres_loc='tzres.dll'):
52 # Load the user32 DLL so we can load strings from tzres
53 user32 = ctypes.WinDLL('user32')
55 # Specify the LoadStringW function
56 user32.LoadStringW.argtypes = (wintypes.HINSTANCE,
57 wintypes.UINT,
58 wintypes.LPWSTR,
59 ctypes.c_int)
61 self.LoadStringW = user32.LoadStringW
62 self._tzres = ctypes.WinDLL(tzres_loc)
63 # PyPy's WinDLL._handle is not a native HMODULE. Keep the DLL loaded
64 # above and ask Windows for its handle instead.
65 kernel32 = ctypes.WinDLL("kernel32")
66 get_module_handle = kernel32.GetModuleHandleW
67 get_module_handle.argtypes = (wintypes.LPCWSTR,)
68 get_module_handle.restype = wintypes.HMODULE
69 self._tzres_handle = get_module_handle(os.path.normpath(tzres_loc))
70 self.tzres_loc = tzres_loc
72 def load_name(self, offset):
73 """
74 Load a timezone name from a DLL offset (integer).
76 >>> from dateutil.tzwin import tzres
77 >>> tzr = tzres()
78 >>> print(tzr.load_name(112))
79 'Eastern Standard Time'
81 :param offset:
82 A positive integer value referring to a string from the tzres dll.
84 .. note::
86 Offsets found in the registry are generally of the form
87 ``@tzres.dll,-114``. The offset in this case is 114, not -114.
89 """
90 resource = self.p_wchar()
91 lpBuffer = ctypes.cast(ctypes.byref(resource), wintypes.LPWSTR)
92 nchar = self.LoadStringW(self._tzres_handle, offset, lpBuffer, 0)
93 return resource[:nchar]
95 def name_from_string(self, tzname_str):
96 """
97 Parse strings as returned from the Windows registry into the time zone
98 name as defined in the registry.
100 >>> from dateutil.tzwin import tzres
101 >>> tzr = tzres()
102 >>> print(tzr.name_from_string('@tzres.dll,-251'))
103 'Dateline Daylight Time'
104 >>> print(tzr.name_from_string('Eastern Standard Time'))
105 'Eastern Standard Time'
107 :param tzname_str:
108 A timezone name string as returned from a Windows registry key.
110 :return:
111 Returns the localized timezone string from tzres.dll if the string
112 is of the form `@tzres.dll,-offset`, else returns the input string.
113 """
114 if not tzname_str.startswith('@'):
115 return tzname_str
117 name_splt = tzname_str.split(',-')
118 try:
119 offset = int(name_splt[1])
120 except:
121 raise ValueError("Malformed timezone string.")
123 return self.load_name(offset)
126class tzwinbase(tzrangebase):
127 """tzinfo class based on win32's timezones available in the registry."""
128 def __init__(self):
129 raise NotImplementedError('tzwinbase is an abstract base class')
131 def __eq__(self, other):
132 # Compare on all relevant dimensions, including name.
133 if not isinstance(other, tzwinbase):
134 return NotImplemented
136 return (self._std_offset == other._std_offset and
137 self._dst_offset == other._dst_offset and
138 self._stddayofweek == other._stddayofweek and
139 self._dstdayofweek == other._dstdayofweek and
140 self._stdweeknumber == other._stdweeknumber and
141 self._dstweeknumber == other._dstweeknumber and
142 self._stdhour == other._stdhour and
143 self._dsthour == other._dsthour and
144 self._stdminute == other._stdminute and
145 self._dstminute == other._dstminute and
146 self._std_abbr == other._std_abbr and
147 self._dst_abbr == other._dst_abbr)
149 @staticmethod
150 def list():
151 """Return a list of all time zones known to the system."""
152 with winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) as handle:
153 with winreg.OpenKey(handle, TZKEYNAME) as tzkey:
154 result = [winreg.EnumKey(tzkey, i)
155 for i in range(winreg.QueryInfoKey(tzkey)[0])]
156 return result
158 def display(self):
159 """
160 Return the display name of the time zone.
161 """
162 return self._display
164 def transitions(self, year):
165 """
166 For a given year, get the DST on and off transition times, expressed
167 always on the standard time side. For zones with no transitions, this
168 function returns ``None``.
170 :param year:
171 The year whose transitions you would like to query.
173 :return:
174 Returns a :class:`tuple` of :class:`datetime.datetime` objects,
175 ``(dston, dstoff)`` for zones with an annual DST transition, or
176 ``None`` for fixed offset zones.
177 """
179 if not self.hasdst:
180 return None
182 dston = picknthweekday(year, self._dstmonth, self._dstdayofweek,
183 self._dsthour, self._dstminute,
184 self._dstweeknumber)
186 dstoff = picknthweekday(year, self._stdmonth, self._stddayofweek,
187 self._stdhour, self._stdminute,
188 self._stdweeknumber)
190 # Ambiguous dates default to the STD side
191 dstoff -= self._dst_base_offset
193 return dston, dstoff
195 def _get_hasdst(self):
196 return self._dstmonth != 0
198 @property
199 def _dst_base_offset(self):
200 return self._dst_base_offset_
203class tzwin(tzwinbase):
204 """
205 Time zone object created from the zone info in the Windows registry
207 These are similar to :py:class:`dateutil.tz.tzrange` objects in that
208 the time zone data is provided in the format of a single offset rule
209 for either 0 or 2 time zone transitions per year.
211 :param: name
212 The name of a Windows time zone key, e.g. "Eastern Standard Time".
213 The full list of keys can be retrieved with :func:`tzwin.list`.
214 """
216 def __init__(self, name):
217 self._name = name
219 with winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) as handle:
220 tzkeyname = "{kn}\\{name}".format(kn=TZKEYNAME, name=name)
221 with winreg.OpenKey(handle, tzkeyname) as tzkey:
222 keydict = valuestodict(tzkey)
224 self._std_abbr = keydict["Std"]
225 self._dst_abbr = keydict["Dlt"]
227 self._display = keydict["Display"]
229 # See http://ww_winreg.jsiinc.com/SUBA/tip0300/rh0398.htm
230 tup = struct.unpack("=3l16h", keydict["TZI"])
231 stdoffset = -tup[0]-tup[1] # Bias + StandardBias * -1
232 dstoffset = stdoffset-tup[2] # + DaylightBias * -1
233 self._std_offset = datetime.timedelta(minutes=stdoffset)
234 self._dst_offset = datetime.timedelta(minutes=dstoffset)
236 # for the meaning see the win32 TIME_ZONE_INFORMATION structure docs
237 # http://msdn.microsoft.com/en-us/library/windows/desktop/ms725481(v=vs.85).aspx
238 (self._stdmonth,
239 self._stddayofweek, # Sunday = 0
240 self._stdweeknumber, # Last = 5
241 self._stdhour,
242 self._stdminute) = tup[4:9]
244 (self._dstmonth,
245 self._dstdayofweek, # Sunday = 0
246 self._dstweeknumber, # Last = 5
247 self._dsthour,
248 self._dstminute) = tup[12:17]
250 self._dst_base_offset_ = self._dst_offset - self._std_offset
251 self.hasdst = self._get_hasdst()
253 def __repr__(self):
254 return "tzwin(%s)" % repr(self._name)
256 def __reduce__(self):
257 return (self.__class__, (self._name,))
260class tzwinlocal(tzwinbase):
261 """
262 Class representing the local time zone information in the Windows registry
264 While :class:`dateutil.tz.tzlocal` makes system calls (via the :mod:`time`
265 module) to retrieve time zone information, ``tzwinlocal`` retrieves the
266 rules directly from the Windows registry and creates an object like
267 :class:`dateutil.tz.tzwin`.
269 Because Windows does not have an equivalent of :func:`time.tzset`, on
270 Windows, :class:`dateutil.tz.tzlocal` instances will always reflect the
271 time zone settings *at the time that the process was started*, meaning
272 changes to the machine's time zone settings during the run of a program
273 on Windows will **not** be reflected by :class:`dateutil.tz.tzlocal`.
274 Because ``tzwinlocal`` reads the registry directly, it is unaffected by
275 this issue.
276 """
277 def __init__(self):
278 with winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) as handle:
279 with winreg.OpenKey(handle, TZLOCALKEYNAME) as tzlocalkey:
280 keydict = valuestodict(tzlocalkey)
282 self._std_abbr = keydict["StandardName"]
283 self._dst_abbr = keydict["DaylightName"]
285 try:
286 tzkeyname = "{kn}\\{sn}".format(kn=TZKEYNAME, sn=self._std_abbr)
287 with winreg.OpenKey(handle, tzkeyname) as tzkey:
288 _keydict = valuestodict(tzkey)
289 self._display = _keydict["Display"]
290 except OSError:
291 self._display = None
293 stdoffset = -keydict["Bias"]-keydict["StandardBias"]
294 dstoffset = stdoffset-keydict["DaylightBias"]
296 self._std_offset = datetime.timedelta(minutes=stdoffset)
297 self._dst_offset = datetime.timedelta(minutes=dstoffset)
299 # For reasons unclear, in this particular key, the day of week has been
300 # moved to the END of the SYSTEMTIME structure.
301 tup = struct.unpack("=8h", keydict["StandardStart"])
303 (self._stdmonth,
304 self._stdweeknumber, # Last = 5
305 self._stdhour,
306 self._stdminute) = tup[1:5]
308 self._stddayofweek = tup[7]
310 tup = struct.unpack("=8h", keydict["DaylightStart"])
312 (self._dstmonth,
313 self._dstweeknumber, # Last = 5
314 self._dsthour,
315 self._dstminute) = tup[1:5]
317 self._dstdayofweek = tup[7]
319 self._dst_base_offset_ = self._dst_offset - self._std_offset
320 self.hasdst = self._get_hasdst()
322 def __repr__(self):
323 return "tzwinlocal()"
325 def __str__(self):
326 # str will return the standard name, not the daylight name.
327 return "tzwinlocal(%s)" % repr(self._std_abbr)
329 def __reduce__(self):
330 return (self.__class__, ())
333def picknthweekday(year, month, dayofweek, hour, minute, whichweek):
334 """ dayofweek == 0 means Sunday, whichweek 5 means last instance """
335 first = datetime.datetime(year, month, 1, hour, minute)
337 # This will work if dayofweek is ISO weekday (1-7) or Microsoft-style (0-6),
338 # Because 7 % 7 = 0
339 weekdayone = first.replace(day=((dayofweek - first.isoweekday()) % 7) + 1)
340 wd = weekdayone + ((whichweek - 1) * ONEWEEK)
341 if (wd.month != month):
342 wd -= ONEWEEK
344 return wd
347def valuestodict(key):
348 """Convert a registry key's values to a dictionary."""
349 dout = {}
350 size = winreg.QueryInfoKey(key)[1]
351 tz_res = None
353 for i in range(size):
354 key_name, value, dtype = winreg.EnumValue(key, i)
355 if dtype == winreg.REG_DWORD or dtype == winreg.REG_DWORD_LITTLE_ENDIAN:
356 # If it's a DWORD (32-bit integer), it's stored as unsigned - convert
357 # that to a proper signed integer
358 if value & (1 << 31):
359 value = value - (1 << 32)
360 elif dtype == winreg.REG_SZ:
361 # If it's a reference to the tzres DLL, load the actual string
362 if value.startswith('@tzres'):
363 tz_res = tz_res or tzres()
364 value = tz_res.name_from_string(value)
366 value = value.rstrip('\x00') # Remove trailing nulls
368 dout[key_name] = value
370 return dout