Path: blob/master/ invest-robot-contest_TinkoffBotTwitch-main/venv/lib/python3.8/site-packages/dateutil/tz/win.py
7763 views
# -*- coding: utf-8 -*-1"""2This module provides an interface to the native time zone data on Windows,3including :py:class:`datetime.tzinfo` implementations.45Attempting to import this module on a non-Windows platform will raise an6:py:obj:`ImportError`.7"""8# This code was originally contributed by Jeffrey Harris.9import datetime10import struct1112from six.moves import winreg13from six import text_type1415try:16import ctypes17from ctypes import wintypes18except ValueError:19# ValueError is raised on non-Windows systems for some horrible reason.20raise ImportError("Running tzwin on non-Windows system")2122from ._common import tzrangebase2324__all__ = ["tzwin", "tzwinlocal", "tzres"]2526ONEWEEK = datetime.timedelta(7)2728TZKEYNAMENT = r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones"29TZKEYNAME9X = r"SOFTWARE\Microsoft\Windows\CurrentVersion\Time Zones"30TZLOCALKEYNAME = r"SYSTEM\CurrentControlSet\Control\TimeZoneInformation"313233def _settzkeyname():34handle = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)35try:36winreg.OpenKey(handle, TZKEYNAMENT).Close()37TZKEYNAME = TZKEYNAMENT38except WindowsError:39TZKEYNAME = TZKEYNAME9X40handle.Close()41return TZKEYNAME424344TZKEYNAME = _settzkeyname()454647class tzres(object):48"""49Class for accessing ``tzres.dll``, which contains timezone name related50resources.5152.. versionadded:: 2.5.053"""54p_wchar = ctypes.POINTER(wintypes.WCHAR) # Pointer to a wide char5556def __init__(self, tzres_loc='tzres.dll'):57# Load the user32 DLL so we can load strings from tzres58user32 = ctypes.WinDLL('user32')5960# Specify the LoadStringW function61user32.LoadStringW.argtypes = (wintypes.HINSTANCE,62wintypes.UINT,63wintypes.LPWSTR,64ctypes.c_int)6566self.LoadStringW = user32.LoadStringW67self._tzres = ctypes.WinDLL(tzres_loc)68self.tzres_loc = tzres_loc6970def load_name(self, offset):71"""72Load a timezone name from a DLL offset (integer).7374>>> from dateutil.tzwin import tzres75>>> tzr = tzres()76>>> print(tzr.load_name(112))77'Eastern Standard Time'7879:param offset:80A positive integer value referring to a string from the tzres dll.8182.. note::8384Offsets found in the registry are generally of the form85``@tzres.dll,-114``. The offset in this case is 114, not -114.8687"""88resource = self.p_wchar()89lpBuffer = ctypes.cast(ctypes.byref(resource), wintypes.LPWSTR)90nchar = self.LoadStringW(self._tzres._handle, offset, lpBuffer, 0)91return resource[:nchar]9293def name_from_string(self, tzname_str):94"""95Parse strings as returned from the Windows registry into the time zone96name as defined in the registry.9798>>> from dateutil.tzwin import tzres99>>> tzr = tzres()100>>> print(tzr.name_from_string('@tzres.dll,-251'))101'Dateline Daylight Time'102>>> print(tzr.name_from_string('Eastern Standard Time'))103'Eastern Standard Time'104105:param tzname_str:106A timezone name string as returned from a Windows registry key.107108:return:109Returns the localized timezone string from tzres.dll if the string110is of the form `@tzres.dll,-offset`, else returns the input string.111"""112if not tzname_str.startswith('@'):113return tzname_str114115name_splt = tzname_str.split(',-')116try:117offset = int(name_splt[1])118except:119raise ValueError("Malformed timezone string.")120121return self.load_name(offset)122123124class tzwinbase(tzrangebase):125"""tzinfo class based on win32's timezones available in the registry."""126def __init__(self):127raise NotImplementedError('tzwinbase is an abstract base class')128129def __eq__(self, other):130# Compare on all relevant dimensions, including name.131if not isinstance(other, tzwinbase):132return NotImplemented133134return (self._std_offset == other._std_offset and135self._dst_offset == other._dst_offset and136self._stddayofweek == other._stddayofweek and137self._dstdayofweek == other._dstdayofweek and138self._stdweeknumber == other._stdweeknumber and139self._dstweeknumber == other._dstweeknumber and140self._stdhour == other._stdhour and141self._dsthour == other._dsthour and142self._stdminute == other._stdminute and143self._dstminute == other._dstminute and144self._std_abbr == other._std_abbr and145self._dst_abbr == other._dst_abbr)146147@staticmethod148def list():149"""Return a list of all time zones known to the system."""150with winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) as handle:151with winreg.OpenKey(handle, TZKEYNAME) as tzkey:152result = [winreg.EnumKey(tzkey, i)153for i in range(winreg.QueryInfoKey(tzkey)[0])]154return result155156def display(self):157"""158Return the display name of the time zone.159"""160return self._display161162def transitions(self, year):163"""164For a given year, get the DST on and off transition times, expressed165always on the standard time side. For zones with no transitions, this166function returns ``None``.167168:param year:169The year whose transitions you would like to query.170171:return:172Returns a :class:`tuple` of :class:`datetime.datetime` objects,173``(dston, dstoff)`` for zones with an annual DST transition, or174``None`` for fixed offset zones.175"""176177if not self.hasdst:178return None179180dston = picknthweekday(year, self._dstmonth, self._dstdayofweek,181self._dsthour, self._dstminute,182self._dstweeknumber)183184dstoff = picknthweekday(year, self._stdmonth, self._stddayofweek,185self._stdhour, self._stdminute,186self._stdweeknumber)187188# Ambiguous dates default to the STD side189dstoff -= self._dst_base_offset190191return dston, dstoff192193def _get_hasdst(self):194return self._dstmonth != 0195196@property197def _dst_base_offset(self):198return self._dst_base_offset_199200201class tzwin(tzwinbase):202"""203Time zone object created from the zone info in the Windows registry204205These are similar to :py:class:`dateutil.tz.tzrange` objects in that206the time zone data is provided in the format of a single offset rule207for either 0 or 2 time zone transitions per year.208209:param: name210The name of a Windows time zone key, e.g. "Eastern Standard Time".211The full list of keys can be retrieved with :func:`tzwin.list`.212"""213214def __init__(self, name):215self._name = name216217with winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) as handle:218tzkeyname = text_type("{kn}\\{name}").format(kn=TZKEYNAME, name=name)219with winreg.OpenKey(handle, tzkeyname) as tzkey:220keydict = valuestodict(tzkey)221222self._std_abbr = keydict["Std"]223self._dst_abbr = keydict["Dlt"]224225self._display = keydict["Display"]226227# See http://ww_winreg.jsiinc.com/SUBA/tip0300/rh0398.htm228tup = struct.unpack("=3l16h", keydict["TZI"])229stdoffset = -tup[0]-tup[1] # Bias + StandardBias * -1230dstoffset = stdoffset-tup[2] # + DaylightBias * -1231self._std_offset = datetime.timedelta(minutes=stdoffset)232self._dst_offset = datetime.timedelta(minutes=dstoffset)233234# for the meaning see the win32 TIME_ZONE_INFORMATION structure docs235# http://msdn.microsoft.com/en-us/library/windows/desktop/ms725481(v=vs.85).aspx236(self._stdmonth,237self._stddayofweek, # Sunday = 0238self._stdweeknumber, # Last = 5239self._stdhour,240self._stdminute) = tup[4:9]241242(self._dstmonth,243self._dstdayofweek, # Sunday = 0244self._dstweeknumber, # Last = 5245self._dsthour,246self._dstminute) = tup[12:17]247248self._dst_base_offset_ = self._dst_offset - self._std_offset249self.hasdst = self._get_hasdst()250251def __repr__(self):252return "tzwin(%s)" % repr(self._name)253254def __reduce__(self):255return (self.__class__, (self._name,))256257258class tzwinlocal(tzwinbase):259"""260Class representing the local time zone information in the Windows registry261262While :class:`dateutil.tz.tzlocal` makes system calls (via the :mod:`time`263module) to retrieve time zone information, ``tzwinlocal`` retrieves the264rules directly from the Windows registry and creates an object like265:class:`dateutil.tz.tzwin`.266267Because Windows does not have an equivalent of :func:`time.tzset`, on268Windows, :class:`dateutil.tz.tzlocal` instances will always reflect the269time zone settings *at the time that the process was started*, meaning270changes to the machine's time zone settings during the run of a program271on Windows will **not** be reflected by :class:`dateutil.tz.tzlocal`.272Because ``tzwinlocal`` reads the registry directly, it is unaffected by273this issue.274"""275def __init__(self):276with winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) as handle:277with winreg.OpenKey(handle, TZLOCALKEYNAME) as tzlocalkey:278keydict = valuestodict(tzlocalkey)279280self._std_abbr = keydict["StandardName"]281self._dst_abbr = keydict["DaylightName"]282283try:284tzkeyname = text_type('{kn}\\{sn}').format(kn=TZKEYNAME,285sn=self._std_abbr)286with winreg.OpenKey(handle, tzkeyname) as tzkey:287_keydict = valuestodict(tzkey)288self._display = _keydict["Display"]289except OSError:290self._display = None291292stdoffset = -keydict["Bias"]-keydict["StandardBias"]293dstoffset = stdoffset-keydict["DaylightBias"]294295self._std_offset = datetime.timedelta(minutes=stdoffset)296self._dst_offset = datetime.timedelta(minutes=dstoffset)297298# For reasons unclear, in this particular key, the day of week has been299# moved to the END of the SYSTEMTIME structure.300tup = struct.unpack("=8h", keydict["StandardStart"])301302(self._stdmonth,303self._stdweeknumber, # Last = 5304self._stdhour,305self._stdminute) = tup[1:5]306307self._stddayofweek = tup[7]308309tup = struct.unpack("=8h", keydict["DaylightStart"])310311(self._dstmonth,312self._dstweeknumber, # Last = 5313self._dsthour,314self._dstminute) = tup[1:5]315316self._dstdayofweek = tup[7]317318self._dst_base_offset_ = self._dst_offset - self._std_offset319self.hasdst = self._get_hasdst()320321def __repr__(self):322return "tzwinlocal()"323324def __str__(self):325# str will return the standard name, not the daylight name.326return "tzwinlocal(%s)" % repr(self._std_abbr)327328def __reduce__(self):329return (self.__class__, ())330331332def picknthweekday(year, month, dayofweek, hour, minute, whichweek):333""" dayofweek == 0 means Sunday, whichweek 5 means last instance """334first = datetime.datetime(year, month, 1, hour, minute)335336# This will work if dayofweek is ISO weekday (1-7) or Microsoft-style (0-6),337# Because 7 % 7 = 0338weekdayone = first.replace(day=((dayofweek - first.isoweekday()) % 7) + 1)339wd = weekdayone + ((whichweek - 1) * ONEWEEK)340if (wd.month != month):341wd -= ONEWEEK342343return wd344345346def valuestodict(key):347"""Convert a registry key's values to a dictionary."""348dout = {}349size = winreg.QueryInfoKey(key)[1]350tz_res = None351352for i in range(size):353key_name, value, dtype = winreg.EnumValue(key, i)354if dtype == winreg.REG_DWORD or dtype == winreg.REG_DWORD_LITTLE_ENDIAN:355# If it's a DWORD (32-bit integer), it's stored as unsigned - convert356# that to a proper signed integer357if value & (1 << 31):358value = value - (1 << 32)359elif dtype == winreg.REG_SZ:360# If it's a reference to the tzres DLL, load the actual string361if value.startswith('@tzres'):362tz_res = tz_res or tzres()363value = tz_res.name_from_string(value)364365value = value.rstrip('\x00') # Remove trailing nulls366367dout[key_name] = value368369return dout370371372