Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

win32timezone.py 34KB

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023
  1. # -*- coding: UTF-8 -*-
  2. """
  3. win32timezone:
  4. Module for handling datetime.tzinfo time zones using the windows
  5. registry for time zone information. The time zone names are dependent
  6. on the registry entries defined by the operating system.
  7. This module may be tested using the doctest module.
  8. Written by Jason R. Coombs (jaraco@jaraco.com).
  9. Copyright © 2003-2012.
  10. All Rights Reserved.
  11. This module is licenced for use in Mark Hammond's pywin32
  12. library under the same terms as the pywin32 library.
  13. To use this time zone module with the datetime module, simply pass
  14. the TimeZoneInfo object to the datetime constructor. For example,
  15. >>> import win32timezone, datetime
  16. >>> assert 'Mountain Standard Time' in win32timezone.TimeZoneInfo.get_sorted_time_zone_names()
  17. >>> MST = win32timezone.TimeZoneInfo('Mountain Standard Time')
  18. >>> now = datetime.datetime.now(MST)
  19. The now object is now a time-zone aware object, and daylight savings-
  20. aware methods may be called on it.
  21. >>> now.utcoffset() in (datetime.timedelta(-1, 61200), datetime.timedelta(-1, 64800))
  22. True
  23. (note that the result of utcoffset call will be different based on when now was
  24. generated, unless standard time is always used)
  25. >>> now = datetime.datetime.now(TimeZoneInfo('Mountain Standard Time', True))
  26. >>> now.utcoffset()
  27. datetime.timedelta(days=-1, seconds=61200)
  28. >>> aug2 = datetime.datetime(2003, 8, 2, tzinfo = MST)
  29. >>> tuple(aug2.utctimetuple())
  30. (2003, 8, 2, 6, 0, 0, 5, 214, 0)
  31. >>> nov2 = datetime.datetime(2003, 11, 25, tzinfo = MST)
  32. >>> tuple(nov2.utctimetuple())
  33. (2003, 11, 25, 7, 0, 0, 1, 329, 0)
  34. To convert from one timezone to another, just use the astimezone method.
  35. >>> aug2.isoformat()
  36. '2003-08-02T00:00:00-06:00'
  37. >>> aug2est = aug2.astimezone(win32timezone.TimeZoneInfo('Eastern Standard Time'))
  38. >>> aug2est.isoformat()
  39. '2003-08-02T02:00:00-04:00'
  40. calling the displayName member will return the display name as set in the
  41. registry.
  42. >>> est = win32timezone.TimeZoneInfo('Eastern Standard Time')
  43. >>> str(est.displayName)
  44. '(UTC-05:00) Eastern Time (US & Canada)'
  45. >>> gmt = win32timezone.TimeZoneInfo('GMT Standard Time', True)
  46. >>> str(gmt.displayName)
  47. '(UTC+00:00) Dublin, Edinburgh, Lisbon, London'
  48. To get the complete list of available time zone keys,
  49. >>> zones = win32timezone.TimeZoneInfo.get_all_time_zones()
  50. If you want to get them in an order that's sorted longitudinally
  51. >>> zones = win32timezone.TimeZoneInfo.get_sorted_time_zones()
  52. TimeZoneInfo now supports being pickled and comparison
  53. >>> import pickle
  54. >>> tz = win32timezone.TimeZoneInfo('China Standard Time')
  55. >>> tz == pickle.loads(pickle.dumps(tz))
  56. True
  57. It's possible to construct a TimeZoneInfo from a TimeZoneDescription
  58. including the currently-defined zone.
  59. >>> tz = win32timezone.TimeZoneInfo(TimeZoneDefinition.current())
  60. >>> tz == pickle.loads(pickle.dumps(tz))
  61. True
  62. >>> aest = win32timezone.TimeZoneInfo('AUS Eastern Standard Time')
  63. >>> est = win32timezone.TimeZoneInfo('E. Australia Standard Time')
  64. >>> dt = datetime.datetime(2006, 11, 11, 1, 0, 0, tzinfo = aest)
  65. >>> estdt = dt.astimezone(est)
  66. >>> estdt.strftime('%Y-%m-%d %H:%M:%S')
  67. '2006-11-11 00:00:00'
  68. >>> dt = datetime.datetime(2007, 1, 12, 1, 0, 0, tzinfo = aest)
  69. >>> estdt = dt.astimezone(est)
  70. >>> estdt.strftime('%Y-%m-%d %H:%M:%S')
  71. '2007-01-12 00:00:00'
  72. >>> dt = datetime.datetime(2007, 6, 13, 1, 0, 0, tzinfo = aest)
  73. >>> estdt = dt.astimezone(est)
  74. >>> estdt.strftime('%Y-%m-%d %H:%M:%S')
  75. '2007-06-13 01:00:00'
  76. Microsoft now has a patch for handling time zones in 2007 (see
  77. http://support.microsoft.com/gp/cp_dst)
  78. As a result, patched systems will give an incorrect result for
  79. dates prior to the designated year except for Vista and its
  80. successors, which have dynamic time zone support.
  81. >>> nov2_pre_change = datetime.datetime(2003, 11, 2, tzinfo = MST)
  82. >>> old_response = (2003, 11, 2, 7, 0, 0, 6, 306, 0)
  83. >>> incorrect_patch_response = (2003, 11, 2, 6, 0, 0, 6, 306, 0)
  84. >>> pre_response = nov2_pre_change.utctimetuple()
  85. >>> pre_response in (old_response, incorrect_patch_response)
  86. True
  87. Furthermore, unpatched systems pre-Vista will give an incorrect
  88. result for dates after 2007.
  89. >>> nov2_post_change = datetime.datetime(2007, 11, 2, tzinfo = MST)
  90. >>> incorrect_unpatched_response = (2007, 11, 2, 7, 0, 0, 4, 306, 0)
  91. >>> new_response = (2007, 11, 2, 6, 0, 0, 4, 306, 0)
  92. >>> post_response = nov2_post_change.utctimetuple()
  93. >>> post_response in (new_response, incorrect_unpatched_response)
  94. True
  95. There is a function you can call to get some capabilities of the time
  96. zone data.
  97. >>> caps = GetTZCapabilities()
  98. >>> isinstance(caps, dict)
  99. True
  100. >>> 'MissingTZPatch' in caps
  101. True
  102. >>> 'DynamicTZSupport' in caps
  103. True
  104. >>> both_dates_correct = (pre_response == old_response and post_response == new_response)
  105. >>> old_dates_wrong = (pre_response == incorrect_patch_response)
  106. >>> new_dates_wrong = (post_response == incorrect_unpatched_response)
  107. >>> caps['DynamicTZSupport'] == both_dates_correct
  108. True
  109. >>> (not caps['DynamicTZSupport'] and caps['MissingTZPatch']) == new_dates_wrong
  110. True
  111. >>> (not caps['DynamicTZSupport'] and not caps['MissingTZPatch']) == old_dates_wrong
  112. True
  113. This test helps ensure language support for unicode characters
  114. >>> x = TIME_ZONE_INFORMATION(0, u'français')
  115. Test conversion from one time zone to another at a DST boundary
  116. ===============================================================
  117. >>> tz_hi = TimeZoneInfo('Hawaiian Standard Time')
  118. >>> tz_pac = TimeZoneInfo('Pacific Standard Time')
  119. >>> time_before = datetime.datetime(2011, 11, 5, 15, 59, 59, tzinfo=tz_hi)
  120. >>> tz_hi.utcoffset(time_before)
  121. datetime.timedelta(days=-1, seconds=50400)
  122. >>> tz_hi.dst(time_before)
  123. datetime.timedelta(0)
  124. Hawaii doesn't need dynamic TZ info
  125. >>> getattr(tz_hi, 'dynamicInfo', None)
  126. Here's a time that gave some trouble as reported in #3523104
  127. because one minute later, the equivalent UTC time changes from DST
  128. in the U.S.
  129. >>> dt_hi = datetime.datetime(2011, 11, 5, 15, 59, 59, 0, tzinfo=tz_hi)
  130. >>> dt_hi.timetuple()
  131. time.struct_time(tm_year=2011, tm_mon=11, tm_mday=5, tm_hour=15, tm_min=59, tm_sec=59, tm_wday=5, tm_yday=309, tm_isdst=0)
  132. >>> dt_hi.utctimetuple()
  133. time.struct_time(tm_year=2011, tm_mon=11, tm_mday=6, tm_hour=1, tm_min=59, tm_sec=59, tm_wday=6, tm_yday=310, tm_isdst=0)
  134. Convert the time to pacific time.
  135. >>> dt_pac = dt_hi.astimezone(tz_pac)
  136. >>> dt_pac.timetuple()
  137. time.struct_time(tm_year=2011, tm_mon=11, tm_mday=5, tm_hour=18, tm_min=59, tm_sec=59, tm_wday=5, tm_yday=309, tm_isdst=1)
  138. Notice that the UTC time is almost 2am.
  139. >>> dt_pac.utctimetuple()
  140. time.struct_time(tm_year=2011, tm_mon=11, tm_mday=6, tm_hour=1, tm_min=59, tm_sec=59, tm_wday=6, tm_yday=310, tm_isdst=0)
  141. Now do the same tests one minute later in Hawaii.
  142. >>> time_after = datetime.datetime(2011, 11, 5, 16, 0, 0, 0, tzinfo=tz_hi)
  143. >>> tz_hi.utcoffset(time_after)
  144. datetime.timedelta(days=-1, seconds=50400)
  145. >>> tz_hi.dst(time_before)
  146. datetime.timedelta(0)
  147. >>> dt_hi = datetime.datetime(2011, 11, 5, 16, 0, 0, 0, tzinfo=tz_hi)
  148. >>> print(dt_hi.timetuple())
  149. time.struct_time(tm_year=2011, tm_mon=11, tm_mday=5, tm_hour=16, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=309, tm_isdst=0)
  150. >>> print(dt_hi.utctimetuple())
  151. time.struct_time(tm_year=2011, tm_mon=11, tm_mday=6, tm_hour=2, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=310, tm_isdst=0)
  152. According to the docs, this is what astimezone does.
  153. >>> utc = (dt_hi - dt_hi.utcoffset()).replace(tzinfo=tz_pac)
  154. >>> utc
  155. datetime.datetime(2011, 11, 6, 2, 0, tzinfo=TimeZoneInfo('Pacific Standard Time'))
  156. >>> tz_pac.fromutc(utc) == dt_hi.astimezone(tz_pac)
  157. True
  158. >>> tz_pac.fromutc(utc)
  159. datetime.datetime(2011, 11, 5, 19, 0, tzinfo=TimeZoneInfo('Pacific Standard Time'))
  160. Make sure the converted time is correct.
  161. >>> dt_pac = dt_hi.astimezone(tz_pac)
  162. >>> dt_pac.timetuple()
  163. time.struct_time(tm_year=2011, tm_mon=11, tm_mday=5, tm_hour=19, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=309, tm_isdst=1)
  164. >>> dt_pac.utctimetuple()
  165. time.struct_time(tm_year=2011, tm_mon=11, tm_mday=6, tm_hour=2, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=310, tm_isdst=0)
  166. Check some internal methods
  167. >>> tz_pac._getStandardBias(datetime.datetime(2011, 1, 1))
  168. datetime.timedelta(seconds=28800)
  169. >>> tz_pac._getDaylightBias(datetime.datetime(2011, 1, 1))
  170. datetime.timedelta(seconds=25200)
  171. Test the offsets
  172. >>> offset = tz_pac.utcoffset(datetime.datetime(2011, 11, 6, 2, 0))
  173. >>> offset == datetime.timedelta(hours=-8)
  174. True
  175. >>> dst_offset = tz_pac.dst(datetime.datetime(2011, 11, 6, 2, 0) + offset)
  176. >>> dst_offset == datetime.timedelta(hours=1)
  177. True
  178. >>> (offset + dst_offset) == datetime.timedelta(hours=-7)
  179. True
  180. Test offsets that occur right at the DST changeover
  181. >>> datetime.datetime.utcfromtimestamp(1320570000).replace(
  182. ... tzinfo=TimeZoneInfo.utc()).astimezone(tz_pac)
  183. datetime.datetime(2011, 11, 6, 1, 0, tzinfo=TimeZoneInfo('Pacific Standard Time'))
  184. """
  185. __author__ = "Jason R. Coombs <jaraco@jaraco.com>"
  186. import datetime
  187. import logging
  188. import operator
  189. import re
  190. import struct
  191. import winreg
  192. from itertools import count
  193. import win32api
  194. log = logging.getLogger(__file__)
  195. # A couple of objects for working with objects as if they were native C-type
  196. # structures.
  197. class _SimpleStruct(object):
  198. _fields_ = None # must be overridden by subclasses
  199. def __init__(self, *args, **kw):
  200. for i, (name, typ) in enumerate(self._fields_):
  201. def_arg = None
  202. if i < len(args):
  203. def_arg = args[i]
  204. if name in kw:
  205. def_arg = kw[name]
  206. if def_arg is not None:
  207. if not isinstance(def_arg, tuple):
  208. def_arg = (def_arg,)
  209. else:
  210. def_arg = ()
  211. if len(def_arg) == 1 and isinstance(def_arg[0], typ):
  212. # already an object of this type.
  213. # XXX - should copy.copy???
  214. def_val = def_arg[0]
  215. else:
  216. def_val = typ(*def_arg)
  217. setattr(self, name, def_val)
  218. def field_names(self):
  219. return [f[0] for f in self._fields_]
  220. def __eq__(self, other):
  221. if not hasattr(other, "_fields_"):
  222. return False
  223. if self._fields_ != other._fields_:
  224. return False
  225. for name, _ in self._fields_:
  226. if getattr(self, name) != getattr(other, name):
  227. return False
  228. return True
  229. def __ne__(self, other):
  230. return not self.__eq__(other)
  231. class SYSTEMTIME(_SimpleStruct):
  232. _fields_ = [
  233. ("year", int),
  234. ("month", int),
  235. ("day_of_week", int),
  236. ("day", int),
  237. ("hour", int),
  238. ("minute", int),
  239. ("second", int),
  240. ("millisecond", int),
  241. ]
  242. class TIME_ZONE_INFORMATION(_SimpleStruct):
  243. _fields_ = [
  244. ("bias", int),
  245. ("standard_name", str),
  246. ("standard_start", SYSTEMTIME),
  247. ("standard_bias", int),
  248. ("daylight_name", str),
  249. ("daylight_start", SYSTEMTIME),
  250. ("daylight_bias", int),
  251. ]
  252. class DYNAMIC_TIME_ZONE_INFORMATION(_SimpleStruct):
  253. _fields_ = TIME_ZONE_INFORMATION._fields_ + [
  254. ("key_name", str),
  255. ("dynamic_daylight_time_disabled", bool),
  256. ]
  257. class TimeZoneDefinition(DYNAMIC_TIME_ZONE_INFORMATION):
  258. """
  259. A time zone definition class based on the win32
  260. DYNAMIC_TIME_ZONE_INFORMATION structure.
  261. Describes a bias against UTC (bias), and two dates at which a separate
  262. additional bias applies (standard_bias and daylight_bias).
  263. """
  264. def __init__(self, *args, **kwargs):
  265. """
  266. Try to construct a TimeZoneDefinition from
  267. a) [DYNAMIC_]TIME_ZONE_INFORMATION args
  268. b) another TimeZoneDefinition
  269. c) a byte structure (using _from_bytes)
  270. """
  271. try:
  272. super(TimeZoneDefinition, self).__init__(*args, **kwargs)
  273. return
  274. except (TypeError, ValueError):
  275. pass
  276. try:
  277. self.__init_from_other(*args, **kwargs)
  278. return
  279. except TypeError:
  280. pass
  281. try:
  282. self.__init_from_bytes(*args, **kwargs)
  283. return
  284. except TypeError:
  285. pass
  286. raise TypeError("Invalid arguments for %s" % self.__class__)
  287. def __init_from_bytes(
  288. self,
  289. bytes,
  290. standard_name="",
  291. daylight_name="",
  292. key_name="",
  293. daylight_disabled=False,
  294. ):
  295. format = "3l8h8h"
  296. components = struct.unpack(format, bytes)
  297. bias, standard_bias, daylight_bias = components[:3]
  298. standard_start = SYSTEMTIME(*components[3:11])
  299. daylight_start = SYSTEMTIME(*components[11:19])
  300. super(TimeZoneDefinition, self).__init__(
  301. bias,
  302. standard_name,
  303. standard_start,
  304. standard_bias,
  305. daylight_name,
  306. daylight_start,
  307. daylight_bias,
  308. key_name,
  309. daylight_disabled,
  310. )
  311. def __init_from_other(self, other):
  312. if not isinstance(other, TIME_ZONE_INFORMATION):
  313. raise TypeError("Not a TIME_ZONE_INFORMATION")
  314. for name in other.field_names():
  315. # explicitly get the value from the underlying structure
  316. value = super(TimeZoneDefinition, other).__getattribute__(other, name)
  317. setattr(self, name, value)
  318. # consider instead of the loop above just copying the memory directly
  319. # size = max(ctypes.sizeof(DYNAMIC_TIME_ZONE_INFO), ctypes.sizeof(other))
  320. # ctypes.memmove(ctypes.addressof(self), other, size)
  321. def __getattribute__(self, attr):
  322. value = super(TimeZoneDefinition, self).__getattribute__(attr)
  323. if "bias" in attr:
  324. value = datetime.timedelta(minutes=value)
  325. return value
  326. @classmethod
  327. def current(class_):
  328. "Windows Platform SDK GetTimeZoneInformation"
  329. code, tzi = win32api.GetTimeZoneInformation(True)
  330. return code, class_(*tzi)
  331. def set(self):
  332. tzi = tuple(getattr(self, n) for n, t in self._fields_)
  333. win32api.SetTimeZoneInformation(tzi)
  334. def copy(self):
  335. # XXX - this is no longer a copy!
  336. return self.__class__(self)
  337. def locate_daylight_start(self, year):
  338. return self._locate_day(year, self.daylight_start)
  339. def locate_standard_start(self, year):
  340. return self._locate_day(year, self.standard_start)
  341. @staticmethod
  342. def _locate_day(year, cutoff):
  343. """
  344. Takes a SYSTEMTIME object, such as retrieved from a TIME_ZONE_INFORMATION
  345. structure or call to GetTimeZoneInformation and interprets it based on the given
  346. year to identify the actual day.
  347. This method is necessary because the SYSTEMTIME structure refers to a day by its
  348. day of the week and week of the month (e.g. 4th saturday in March).
  349. >>> SATURDAY = 6
  350. >>> MARCH = 3
  351. >>> st = SYSTEMTIME(2000, MARCH, SATURDAY, 4, 0, 0, 0, 0)
  352. # according to my calendar, the 4th Saturday in March in 2009 was the 28th
  353. >>> expected_date = datetime.datetime(2009, 3, 28)
  354. >>> TimeZoneDefinition._locate_day(2009, st) == expected_date
  355. True
  356. """
  357. # MS stores Sunday as 0, Python datetime stores Monday as zero
  358. target_weekday = (cutoff.day_of_week + 6) % 7
  359. # For SYSTEMTIMEs relating to time zone inforamtion, cutoff.day
  360. # is the week of the month
  361. week_of_month = cutoff.day
  362. # so the following is the first day of that week
  363. day = (week_of_month - 1) * 7 + 1
  364. result = datetime.datetime(
  365. year,
  366. cutoff.month,
  367. day,
  368. cutoff.hour,
  369. cutoff.minute,
  370. cutoff.second,
  371. cutoff.millisecond,
  372. )
  373. # now the result is the correct week, but not necessarily the correct day of the week
  374. days_to_go = (target_weekday - result.weekday()) % 7
  375. result += datetime.timedelta(days_to_go)
  376. # if we selected a day in the month following the target month,
  377. # move back a week or two.
  378. # This is necessary because Microsoft defines the fifth week in a month
  379. # to be the last week in a month and adding the time delta might have
  380. # pushed the result into the next month.
  381. while result.month == cutoff.month + 1:
  382. result -= datetime.timedelta(weeks=1)
  383. return result
  384. class TimeZoneInfo(datetime.tzinfo):
  385. """
  386. Main class for handling Windows time zones.
  387. Usage:
  388. TimeZoneInfo(<Time Zone Standard Name>, [<Fix Standard Time>])
  389. If <Fix Standard Time> evaluates to True, daylight savings time is
  390. calculated in the same way as standard time.
  391. >>> tzi = TimeZoneInfo('Pacific Standard Time')
  392. >>> march31 = datetime.datetime(2000,3,31)
  393. We know that time zone definitions haven't changed from 2007
  394. to 2012, so regardless of whether dynamic info is available,
  395. there should be consistent results for these years.
  396. >>> subsequent_years = [march31.replace(year=year)
  397. ... for year in range(2007, 2013)]
  398. >>> offsets = set(tzi.utcoffset(year) for year in subsequent_years)
  399. >>> len(offsets)
  400. 1
  401. """
  402. # this key works for WinNT+, but not for the Win95 line.
  403. tzRegKey = r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones"
  404. def __init__(self, param=None, fix_standard_time=False):
  405. if isinstance(param, TimeZoneDefinition):
  406. self._LoadFromTZI(param)
  407. if isinstance(param, str):
  408. self.timeZoneName = param
  409. self._LoadInfoFromKey()
  410. self.fixedStandardTime = fix_standard_time
  411. def _FindTimeZoneKey(self):
  412. """Find the registry key for the time zone name (self.timeZoneName)."""
  413. # for multi-language compatability, match the time zone name in the
  414. # "Std" key of the time zone key.
  415. zoneNames = dict(self._get_indexed_time_zone_keys("Std"))
  416. # Also match the time zone key name itself, to be compatible with
  417. # English-based hard-coded time zones.
  418. timeZoneName = zoneNames.get(self.timeZoneName, self.timeZoneName)
  419. key = _RegKeyDict.open(winreg.HKEY_LOCAL_MACHINE, self.tzRegKey)
  420. try:
  421. result = key.subkey(timeZoneName)
  422. except Exception:
  423. raise ValueError("Timezone Name %s not found." % timeZoneName)
  424. return result
  425. def _LoadInfoFromKey(self):
  426. """Loads the information from an opened time zone registry key
  427. into relevant fields of this TZI object"""
  428. key = self._FindTimeZoneKey()
  429. self.displayName = key["Display"]
  430. self.standardName = key["Std"]
  431. self.daylightName = key["Dlt"]
  432. self.staticInfo = TimeZoneDefinition(key["TZI"])
  433. self._LoadDynamicInfoFromKey(key)
  434. def _LoadFromTZI(self, tzi):
  435. self.timeZoneName = tzi.standard_name
  436. self.displayName = "Unknown"
  437. self.standardName = tzi.standard_name
  438. self.daylightName = tzi.daylight_name
  439. self.staticInfo = tzi
  440. def _LoadDynamicInfoFromKey(self, key):
  441. """
  442. >>> tzi = TimeZoneInfo('Central Standard Time')
  443. Here's how the RangeMap is supposed to work:
  444. >>> m = RangeMap(zip([2006,2007], 'BC'),
  445. ... sort_params = dict(reverse=True),
  446. ... key_match_comparator=operator.ge)
  447. >>> m.get(2000, 'A')
  448. 'A'
  449. >>> m[2006]
  450. 'B'
  451. >>> m[2007]
  452. 'C'
  453. >>> m[2008]
  454. 'C'
  455. >>> m[RangeMap.last_item]
  456. 'B'
  457. >>> m.get(2008, m[RangeMap.last_item])
  458. 'C'
  459. Now test the dynamic info (but fallback to our simple RangeMap
  460. on systems that don't have dynamicInfo).
  461. >>> dinfo = getattr(tzi, 'dynamicInfo', m)
  462. >>> 2007 in dinfo
  463. True
  464. >>> 2008 in dinfo
  465. False
  466. >>> dinfo[2007] == dinfo[2008] == dinfo[2012]
  467. True
  468. """
  469. try:
  470. info = key.subkey("Dynamic DST")
  471. except WindowsError:
  472. return
  473. del info["FirstEntry"]
  474. del info["LastEntry"]
  475. years = map(int, list(info.keys()))
  476. values = map(TimeZoneDefinition, list(info.values()))
  477. # create a range mapping that searches by descending year and matches
  478. # if the target year is greater or equal.
  479. self.dynamicInfo = RangeMap(
  480. zip(years, values),
  481. sort_params=dict(reverse=True),
  482. key_match_comparator=operator.ge,
  483. )
  484. def __repr__(self):
  485. result = "%s(%s" % (self.__class__.__name__, repr(self.timeZoneName))
  486. if self.fixedStandardTime:
  487. result += ", True"
  488. result += ")"
  489. return result
  490. def __str__(self):
  491. return self.displayName
  492. def tzname(self, dt):
  493. winInfo = self.getWinInfo(dt)
  494. if self.dst(dt) == winInfo.daylight_bias:
  495. result = self.daylightName
  496. elif self.dst(dt) == winInfo.standard_bias:
  497. result = self.standardName
  498. return result
  499. def getWinInfo(self, targetYear):
  500. """
  501. Return the most relevant "info" for this time zone
  502. in the target year.
  503. """
  504. if not hasattr(self, "dynamicInfo") or not self.dynamicInfo:
  505. return self.staticInfo
  506. # Find the greatest year entry in self.dynamicInfo which is for
  507. # a year greater than or equal to our targetYear. If not found,
  508. # default to the earliest year.
  509. return self.dynamicInfo.get(targetYear, self.dynamicInfo[RangeMap.last_item])
  510. def _getStandardBias(self, dt):
  511. winInfo = self.getWinInfo(dt.year)
  512. return winInfo.bias + winInfo.standard_bias
  513. def _getDaylightBias(self, dt):
  514. winInfo = self.getWinInfo(dt.year)
  515. return winInfo.bias + winInfo.daylight_bias
  516. def utcoffset(self, dt):
  517. "Calculates the utcoffset according to the datetime.tzinfo spec"
  518. if dt is None:
  519. return
  520. winInfo = self.getWinInfo(dt.year)
  521. return -winInfo.bias + self.dst(dt)
  522. def dst(self, dt):
  523. """
  524. Calculate the daylight savings offset according to the
  525. datetime.tzinfo spec.
  526. """
  527. if dt is None:
  528. return
  529. winInfo = self.getWinInfo(dt.year)
  530. if not self.fixedStandardTime and self._inDaylightSavings(dt):
  531. result = winInfo.daylight_bias
  532. else:
  533. result = winInfo.standard_bias
  534. return -result
  535. def _inDaylightSavings(self, dt):
  536. dt = dt.replace(tzinfo=None)
  537. winInfo = self.getWinInfo(dt.year)
  538. try:
  539. dstStart = self.GetDSTStartTime(dt.year)
  540. dstEnd = self.GetDSTEndTime(dt.year)
  541. # at the end of DST, when clocks are moved back, there's a period
  542. # of daylight_bias where it's ambiguous whether we're in DST or
  543. # not.
  544. dstEndAdj = dstEnd + winInfo.daylight_bias
  545. # the same thing could theoretically happen at the start of DST
  546. # if there's a standard_bias (which I suspect is always 0).
  547. dstStartAdj = dstStart + winInfo.standard_bias
  548. if dstStart < dstEnd:
  549. in_dst = dstStartAdj <= dt < dstEndAdj
  550. else:
  551. # in the southern hemisphere, daylight savings time
  552. # typically ends before it begins in a given year.
  553. in_dst = not (dstEndAdj < dt <= dstStartAdj)
  554. except ValueError:
  555. # there was an error parsing the time zone, which is normal when a
  556. # start and end time are not specified.
  557. in_dst = False
  558. return in_dst
  559. def GetDSTStartTime(self, year):
  560. "Given a year, determines the time when daylight savings time starts"
  561. return self.getWinInfo(year).locate_daylight_start(year)
  562. def GetDSTEndTime(self, year):
  563. "Given a year, determines the time when daylight savings ends."
  564. return self.getWinInfo(year).locate_standard_start(year)
  565. def __cmp__(self, other):
  566. return cmp(self.__dict__, other.__dict__)
  567. def __eq__(self, other):
  568. return self.__dict__ == other.__dict__
  569. def __ne__(self, other):
  570. return self.__dict__ != other.__dict__
  571. @classmethod
  572. def local(class_):
  573. """Returns the local time zone as defined by the operating system in the
  574. registry.
  575. >>> localTZ = TimeZoneInfo.local()
  576. >>> now_local = datetime.datetime.now(localTZ)
  577. >>> now_UTC = datetime.datetime.utcnow()
  578. >>> (now_UTC - now_local) < datetime.timedelta(seconds = 5)
  579. Traceback (most recent call last):
  580. ...
  581. TypeError: can't subtract offset-naive and offset-aware datetimes
  582. >>> now_UTC = now_UTC.replace(tzinfo = TimeZoneInfo('GMT Standard Time', True))
  583. Now one can compare the results of the two offset aware values
  584. >>> (now_UTC - now_local) < datetime.timedelta(seconds = 5)
  585. True
  586. """
  587. code, info = TimeZoneDefinition.current()
  588. # code is 0 if daylight savings is disabled or not defined
  589. # code is 1 or 2 if daylight savings is enabled, 2 if currently active
  590. fix_standard_time = not code
  591. # note that although the given information is sufficient
  592. # to construct a WinTZI object, it's
  593. # not sufficient to represent the time zone in which
  594. # the current user is operating due
  595. # to dynamic time zones.
  596. return class_(info, fix_standard_time)
  597. @classmethod
  598. def utc(class_):
  599. """Returns a time-zone representing UTC.
  600. Same as TimeZoneInfo('GMT Standard Time', True) but caches the result
  601. for performance.
  602. >>> isinstance(TimeZoneInfo.utc(), TimeZoneInfo)
  603. True
  604. """
  605. if "_tzutc" not in class_.__dict__:
  606. setattr(class_, "_tzutc", class_("GMT Standard Time", True))
  607. return class_._tzutc
  608. # helper methods for accessing the timezone info from the registry
  609. @staticmethod
  610. def _get_time_zone_key(subkey=None):
  611. "Return the registry key that stores time zone details"
  612. key = _RegKeyDict.open(winreg.HKEY_LOCAL_MACHINE, TimeZoneInfo.tzRegKey)
  613. if subkey:
  614. key = key.subkey(subkey)
  615. return key
  616. @staticmethod
  617. def _get_time_zone_key_names():
  618. "Returns the names of the (registry keys of the) time zones"
  619. return TimeZoneInfo._get_time_zone_key().subkeys()
  620. @staticmethod
  621. def _get_indexed_time_zone_keys(index_key="Index"):
  622. """
  623. Get the names of the registry keys indexed by a value in that key,
  624. ignoring any keys for which that value is empty or missing.
  625. """
  626. key_names = list(TimeZoneInfo._get_time_zone_key_names())
  627. def get_index_value(key_name):
  628. key = TimeZoneInfo._get_time_zone_key(key_name)
  629. return key.get(index_key)
  630. values = map(get_index_value, key_names)
  631. return (
  632. (value, key_name) for value, key_name in zip(values, key_names) if value
  633. )
  634. @staticmethod
  635. def get_sorted_time_zone_names():
  636. """
  637. Return a list of time zone names that can
  638. be used to initialize TimeZoneInfo instances.
  639. """
  640. tzs = TimeZoneInfo.get_sorted_time_zones()
  641. return [tz.standardName for tz in tzs]
  642. @staticmethod
  643. def get_all_time_zones():
  644. return [TimeZoneInfo(n) for n in TimeZoneInfo._get_time_zone_key_names()]
  645. @staticmethod
  646. def get_sorted_time_zones(key=None):
  647. """
  648. Return the time zones sorted by some key.
  649. key must be a function that takes a TimeZoneInfo object and returns
  650. a value suitable for sorting on.
  651. The key defaults to the bias (descending), as is done in Windows
  652. (see http://blogs.msdn.com/michkap/archive/2006/12/22/1350684.aspx)
  653. """
  654. key = key or (lambda tzi: -tzi.staticInfo.bias)
  655. zones = TimeZoneInfo.get_all_time_zones()
  656. zones.sort(key=key)
  657. return zones
  658. class _RegKeyDict(dict):
  659. def __init__(self, key):
  660. dict.__init__(self)
  661. self.key = key
  662. self.__load_values()
  663. @classmethod
  664. def open(cls, *args, **kargs):
  665. return _RegKeyDict(winreg.OpenKeyEx(*args, **kargs))
  666. def subkey(self, name):
  667. return _RegKeyDict(winreg.OpenKeyEx(self.key, name))
  668. def __load_values(self):
  669. pairs = [(n, v) for (n, v, t) in self._enumerate_reg_values(self.key)]
  670. self.update(pairs)
  671. def subkeys(self):
  672. return self._enumerate_reg_keys(self.key)
  673. @staticmethod
  674. def _enumerate_reg_values(key):
  675. return _RegKeyDict._enumerate_reg(key, winreg.EnumValue)
  676. @staticmethod
  677. def _enumerate_reg_keys(key):
  678. return _RegKeyDict._enumerate_reg(key, winreg.EnumKey)
  679. @staticmethod
  680. def _enumerate_reg(key, func):
  681. "Enumerates an open registry key as an iterable generator"
  682. try:
  683. for index in count():
  684. yield func(key, index)
  685. except WindowsError:
  686. pass
  687. def utcnow():
  688. """
  689. Return the UTC time now with timezone awareness as enabled
  690. by this module
  691. >>> now = utcnow()
  692. """
  693. now = datetime.datetime.utcnow()
  694. now = now.replace(tzinfo=TimeZoneInfo.utc())
  695. return now
  696. def now():
  697. """
  698. Return the local time now with timezone awareness as enabled
  699. by this module
  700. >>> now_local = now()
  701. """
  702. return datetime.datetime.now(TimeZoneInfo.local())
  703. def GetTZCapabilities():
  704. """
  705. Run a few known tests to determine the capabilities of
  706. the time zone database on this machine.
  707. Note Dynamic Time Zone support is not available on any
  708. platform at this time; this
  709. is a limitation of this library, not the platform."""
  710. tzi = TimeZoneInfo("Mountain Standard Time")
  711. MissingTZPatch = datetime.datetime(2007, 11, 2, tzinfo=tzi).utctimetuple() != (
  712. 2007,
  713. 11,
  714. 2,
  715. 6,
  716. 0,
  717. 0,
  718. 4,
  719. 306,
  720. 0,
  721. )
  722. DynamicTZSupport = not MissingTZPatch and datetime.datetime(
  723. 2003, 11, 2, tzinfo=tzi
  724. ).utctimetuple() == (2003, 11, 2, 7, 0, 0, 6, 306, 0)
  725. del tzi
  726. return locals()
  727. class DLLHandleCache(object):
  728. def __init__(self):
  729. self.__cache = {}
  730. def __getitem__(self, filename):
  731. key = filename.lower()
  732. return self.__cache.setdefault(key, win32api.LoadLibrary(key))
  733. DLLCache = DLLHandleCache()
  734. def resolveMUITimeZone(spec):
  735. """Resolve a multilingual user interface resource for the time zone name
  736. >>> #some pre-amble for the doc-tests to be py2k and py3k aware)
  737. >>> try: unicode and None
  738. ... except NameError: unicode=str
  739. ...
  740. >>> import sys
  741. >>> result = resolveMUITimeZone('@tzres.dll,-110')
  742. >>> expectedResultType = [type(None),unicode][sys.getwindowsversion() >= (6,)]
  743. >>> type(result) is expectedResultType
  744. True
  745. spec should be of the format @path,-stringID[;comment]
  746. see http://msdn2.microsoft.com/en-us/library/ms725481.aspx for details
  747. """
  748. pattern = re.compile(r"@(?P<dllname>.*),-(?P<index>\d+)(?:;(?P<comment>.*))?")
  749. matcher = pattern.match(spec)
  750. assert matcher, "Could not parse MUI spec"
  751. try:
  752. handle = DLLCache[matcher.groupdict()["dllname"]]
  753. result = win32api.LoadString(handle, int(matcher.groupdict()["index"]))
  754. except win32api.error:
  755. result = None
  756. return result
  757. # from jaraco.util.dictlib 5.3.1
  758. class RangeMap(dict):
  759. """
  760. A dictionary-like object that uses the keys as bounds for a range.
  761. Inclusion of the value for that range is determined by the
  762. key_match_comparator, which defaults to less-than-or-equal.
  763. A value is returned for a key if it is the first key that matches in
  764. the sorted list of keys.
  765. One may supply keyword parameters to be passed to the sort function used
  766. to sort keys (i.e. cmp [python 2 only], keys, reverse) as sort_params.
  767. Let's create a map that maps 1-3 -> 'a', 4-6 -> 'b'
  768. >>> r = RangeMap({3: 'a', 6: 'b'}) # boy, that was easy
  769. >>> r[1], r[2], r[3], r[4], r[5], r[6]
  770. ('a', 'a', 'a', 'b', 'b', 'b')
  771. Even float values should work so long as the comparison operator
  772. supports it.
  773. >>> r[4.5]
  774. 'b'
  775. But you'll notice that the way rangemap is defined, it must be open-ended on one side.
  776. >>> r[0]
  777. 'a'
  778. >>> r[-1]
  779. 'a'
  780. One can close the open-end of the RangeMap by using undefined_value
  781. >>> r = RangeMap({0: RangeMap.undefined_value, 3: 'a', 6: 'b'})
  782. >>> r[0]
  783. Traceback (most recent call last):
  784. ...
  785. KeyError: 0
  786. One can get the first or last elements in the range by using RangeMap.Item
  787. >>> last_item = RangeMap.Item(-1)
  788. >>> r[last_item]
  789. 'b'
  790. .last_item is a shortcut for Item(-1)
  791. >>> r[RangeMap.last_item]
  792. 'b'
  793. Sometimes it's useful to find the bounds for a RangeMap
  794. >>> r.bounds()
  795. (0, 6)
  796. RangeMap supports .get(key, default)
  797. >>> r.get(0, 'not found')
  798. 'not found'
  799. >>> r.get(7, 'not found')
  800. 'not found'
  801. """
  802. def __init__(self, source, sort_params={}, key_match_comparator=operator.le):
  803. dict.__init__(self, source)
  804. self.sort_params = sort_params
  805. self.match = key_match_comparator
  806. def __getitem__(self, item):
  807. sorted_keys = sorted(list(self.keys()), **self.sort_params)
  808. if isinstance(item, RangeMap.Item):
  809. result = self.__getitem__(sorted_keys[item])
  810. else:
  811. key = self._find_first_match_(sorted_keys, item)
  812. result = dict.__getitem__(self, key)
  813. if result is RangeMap.undefined_value:
  814. raise KeyError(key)
  815. return result
  816. def get(self, key, default=None):
  817. """
  818. Return the value for key if key is in the dictionary, else default.
  819. If default is not given, it defaults to None, so that this method
  820. never raises a KeyError.
  821. """
  822. try:
  823. return self[key]
  824. except KeyError:
  825. return default
  826. def _find_first_match_(self, keys, item):
  827. def is_match(k):
  828. return self.match(item, k)
  829. matches = list(filter(is_match, keys))
  830. if matches:
  831. return matches[0]
  832. raise KeyError(item)
  833. def bounds(self):
  834. sorted_keys = sorted(list(self.keys()), **self.sort_params)
  835. return (
  836. sorted_keys[RangeMap.first_item],
  837. sorted_keys[RangeMap.last_item],
  838. )
  839. # some special values for the RangeMap
  840. undefined_value = type(str("RangeValueUndefined"), (object,), {})()
  841. class Item(int):
  842. pass
  843. first_item = Item(0)
  844. last_item = Item(-1)