win32timezone.py 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003
  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 winreg
  187. import struct
  188. import datetime
  189. import win32api
  190. import re
  191. import operator
  192. from itertools import count
  193. import logging
  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, bytes, standard_name='', daylight_name='', key_name='',
  289. daylight_disabled=False):
  290. format = '3l8h8h'
  291. components = struct.unpack(format, bytes)
  292. bias, standard_bias, daylight_bias = components[:3]
  293. standard_start = SYSTEMTIME(*components[3:11])
  294. daylight_start = SYSTEMTIME(*components[11:19])
  295. super(TimeZoneDefinition, self).__init__(
  296. bias,
  297. standard_name, standard_start, standard_bias,
  298. daylight_name, daylight_start, daylight_bias,
  299. key_name, daylight_disabled,)
  300. def __init_from_other(self, other):
  301. if not isinstance(other, TIME_ZONE_INFORMATION):
  302. raise TypeError("Not a TIME_ZONE_INFORMATION")
  303. for name in other.field_names():
  304. # explicitly get the value from the underlying structure
  305. value = super(TimeZoneDefinition, other).__getattribute__(other, name)
  306. setattr(self, name, value)
  307. # consider instead of the loop above just copying the memory directly
  308. # size = max(ctypes.sizeof(DYNAMIC_TIME_ZONE_INFO), ctypes.sizeof(other))
  309. # ctypes.memmove(ctypes.addressof(self), other, size)
  310. def __getattribute__(self, attr):
  311. value = super(TimeZoneDefinition, self).__getattribute__(attr)
  312. if 'bias' in attr:
  313. value = datetime.timedelta(minutes=value)
  314. return value
  315. @classmethod
  316. def current(class_):
  317. "Windows Platform SDK GetTimeZoneInformation"
  318. code, tzi = win32api.GetTimeZoneInformation(True)
  319. return code, class_(*tzi)
  320. def set(self):
  321. tzi = tuple(getattr(self, n) for n, t in self._fields_)
  322. win32api.SetTimeZoneInformation(tzi)
  323. def copy(self):
  324. # XXX - this is no longer a copy!
  325. return self.__class__(self)
  326. def locate_daylight_start(self, year):
  327. return self._locate_day(year, self.daylight_start)
  328. def locate_standard_start(self, year):
  329. return self._locate_day(year, self.standard_start)
  330. @staticmethod
  331. def _locate_day(year, cutoff):
  332. """
  333. Takes a SYSTEMTIME object, such as retrieved from a TIME_ZONE_INFORMATION
  334. structure or call to GetTimeZoneInformation and interprets it based on the given
  335. year to identify the actual day.
  336. This method is necessary because the SYSTEMTIME structure refers to a day by its
  337. day of the week and week of the month (e.g. 4th saturday in March).
  338. >>> SATURDAY = 6
  339. >>> MARCH = 3
  340. >>> st = SYSTEMTIME(2000, MARCH, SATURDAY, 4, 0, 0, 0, 0)
  341. # according to my calendar, the 4th Saturday in March in 2009 was the 28th
  342. >>> expected_date = datetime.datetime(2009, 3, 28)
  343. >>> TimeZoneDefinition._locate_day(2009, st) == expected_date
  344. True
  345. """
  346. # MS stores Sunday as 0, Python datetime stores Monday as zero
  347. target_weekday = (cutoff.day_of_week + 6) % 7
  348. # For SYSTEMTIMEs relating to time zone inforamtion, cutoff.day
  349. # is the week of the month
  350. week_of_month = cutoff.day
  351. # so the following is the first day of that week
  352. day = (week_of_month - 1) * 7 + 1
  353. result = datetime.datetime(
  354. year, cutoff.month, day,
  355. cutoff.hour, cutoff.minute, cutoff.second, cutoff.millisecond)
  356. # now the result is the correct week, but not necessarily the correct day of the week
  357. days_to_go = (target_weekday - result.weekday()) % 7
  358. result += datetime.timedelta(days_to_go)
  359. # if we selected a day in the month following the target month,
  360. # move back a week or two.
  361. # This is necessary because Microsoft defines the fifth week in a month
  362. # to be the last week in a month and adding the time delta might have
  363. # pushed the result into the next month.
  364. while result.month == cutoff.month + 1:
  365. result -= datetime.timedelta(weeks = 1)
  366. return result
  367. class TimeZoneInfo(datetime.tzinfo):
  368. """
  369. Main class for handling Windows time zones.
  370. Usage:
  371. TimeZoneInfo(<Time Zone Standard Name>, [<Fix Standard Time>])
  372. If <Fix Standard Time> evaluates to True, daylight savings time is
  373. calculated in the same way as standard time.
  374. >>> tzi = TimeZoneInfo('Pacific Standard Time')
  375. >>> march31 = datetime.datetime(2000,3,31)
  376. We know that time zone definitions haven't changed from 2007
  377. to 2012, so regardless of whether dynamic info is available,
  378. there should be consistent results for these years.
  379. >>> subsequent_years = [march31.replace(year=year)
  380. ... for year in range(2007, 2013)]
  381. >>> offsets = set(tzi.utcoffset(year) for year in subsequent_years)
  382. >>> len(offsets)
  383. 1
  384. """
  385. # this key works for WinNT+, but not for the Win95 line.
  386. tzRegKey = r'SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones'
  387. def __init__(self, param=None, fix_standard_time=False):
  388. if isinstance(param, TimeZoneDefinition):
  389. self._LoadFromTZI(param)
  390. if isinstance(param, str):
  391. self.timeZoneName = param
  392. self._LoadInfoFromKey()
  393. self.fixedStandardTime = fix_standard_time
  394. def _FindTimeZoneKey(self):
  395. """Find the registry key for the time zone name (self.timeZoneName)."""
  396. # for multi-language compatability, match the time zone name in the
  397. # "Std" key of the time zone key.
  398. zoneNames = dict(self._get_indexed_time_zone_keys('Std'))
  399. # Also match the time zone key name itself, to be compatible with
  400. # English-based hard-coded time zones.
  401. timeZoneName = zoneNames.get(self.timeZoneName, self.timeZoneName)
  402. key = _RegKeyDict.open(winreg.HKEY_LOCAL_MACHINE, self.tzRegKey)
  403. try:
  404. result = key.subkey(timeZoneName)
  405. except Exception:
  406. raise ValueError('Timezone Name %s not found.' % timeZoneName)
  407. return result
  408. def _LoadInfoFromKey(self):
  409. """Loads the information from an opened time zone registry key
  410. into relevant fields of this TZI object"""
  411. key = self._FindTimeZoneKey()
  412. self.displayName = key['Display']
  413. self.standardName = key['Std']
  414. self.daylightName = key['Dlt']
  415. self.staticInfo = TimeZoneDefinition(key['TZI'])
  416. self._LoadDynamicInfoFromKey(key)
  417. def _LoadFromTZI(self, tzi):
  418. self.timeZoneName = tzi.standard_name
  419. self.displayName = 'Unknown'
  420. self.standardName = tzi.standard_name
  421. self.daylightName = tzi.daylight_name
  422. self.staticInfo = tzi
  423. def _LoadDynamicInfoFromKey(self, key):
  424. """
  425. >>> tzi = TimeZoneInfo('Central Standard Time')
  426. Here's how the RangeMap is supposed to work:
  427. >>> m = RangeMap(zip([2006,2007], 'BC'),
  428. ... sort_params = dict(reverse=True),
  429. ... key_match_comparator=operator.ge)
  430. >>> m.get(2000, 'A')
  431. 'A'
  432. >>> m[2006]
  433. 'B'
  434. >>> m[2007]
  435. 'C'
  436. >>> m[2008]
  437. 'C'
  438. >>> m[RangeMap.last_item]
  439. 'B'
  440. >>> m.get(2008, m[RangeMap.last_item])
  441. 'C'
  442. Now test the dynamic info (but fallback to our simple RangeMap
  443. on systems that don't have dynamicInfo).
  444. >>> dinfo = getattr(tzi, 'dynamicInfo', m)
  445. >>> 2007 in dinfo
  446. True
  447. >>> 2008 in dinfo
  448. False
  449. >>> dinfo[2007] == dinfo[2008] == dinfo[2012]
  450. True
  451. """
  452. try:
  453. info = key.subkey('Dynamic DST')
  454. except WindowsError:
  455. return
  456. del info['FirstEntry']
  457. del info['LastEntry']
  458. years = map(int, list(info.keys()))
  459. values = map(TimeZoneDefinition, list(info.values()))
  460. # create a range mapping that searches by descending year and matches
  461. # if the target year is greater or equal.
  462. self.dynamicInfo = RangeMap(
  463. zip(years, values),
  464. sort_params=dict(reverse=True),
  465. key_match_comparator=operator.ge)
  466. def __repr__(self):
  467. result = '%s(%s' % (self.__class__.__name__, repr(self.timeZoneName))
  468. if self.fixedStandardTime:
  469. result += ', True'
  470. result += ')'
  471. return result
  472. def __str__(self):
  473. return self.displayName
  474. def tzname(self, dt):
  475. winInfo = self.getWinInfo(dt)
  476. if self.dst(dt) == winInfo.daylight_bias:
  477. result = self.daylightName
  478. elif self.dst(dt) == winInfo.standard_bias:
  479. result = self.standardName
  480. return result
  481. def getWinInfo(self, targetYear):
  482. """
  483. Return the most relevant "info" for this time zone
  484. in the target year.
  485. """
  486. if not hasattr(self, 'dynamicInfo') or not self.dynamicInfo:
  487. return self.staticInfo
  488. # Find the greatest year entry in self.dynamicInfo which is for
  489. # a year greater than or equal to our targetYear. If not found,
  490. # default to the earliest year.
  491. return self.dynamicInfo.get(
  492. targetYear, self.dynamicInfo[RangeMap.last_item])
  493. def _getStandardBias(self, dt):
  494. winInfo = self.getWinInfo(dt.year)
  495. return winInfo.bias + winInfo.standard_bias
  496. def _getDaylightBias(self, dt):
  497. winInfo = self.getWinInfo(dt.year)
  498. return winInfo.bias + winInfo.daylight_bias
  499. def utcoffset(self, dt):
  500. "Calculates the utcoffset according to the datetime.tzinfo spec"
  501. if dt is None:
  502. return
  503. winInfo = self.getWinInfo(dt.year)
  504. return -winInfo.bias + self.dst(dt)
  505. def dst(self, dt):
  506. """
  507. Calculate the daylight savings offset according to the
  508. datetime.tzinfo spec.
  509. """
  510. if dt is None:
  511. return
  512. winInfo = self.getWinInfo(dt.year)
  513. if not self.fixedStandardTime and self._inDaylightSavings(dt):
  514. result = winInfo.daylight_bias
  515. else:
  516. result = winInfo.standard_bias
  517. return -result
  518. def _inDaylightSavings(self, dt):
  519. dt = dt.replace(tzinfo=None)
  520. winInfo = self.getWinInfo(dt.year)
  521. try:
  522. dstStart = self.GetDSTStartTime(dt.year)
  523. dstEnd = self.GetDSTEndTime(dt.year)
  524. # at the end of DST, when clocks are moved back, there's a period
  525. # of daylight_bias where it's ambiguous whether we're in DST or
  526. # not.
  527. dstEndAdj = dstEnd + winInfo.daylight_bias
  528. # the same thing could theoretically happen at the start of DST
  529. # if there's a standard_bias (which I suspect is always 0).
  530. dstStartAdj = dstStart + winInfo.standard_bias
  531. if dstStart < dstEnd:
  532. in_dst = dstStartAdj <= dt < dstEndAdj
  533. else:
  534. # in the southern hemisphere, daylight savings time
  535. # typically ends before it begins in a given year.
  536. in_dst = not (dstEndAdj < dt <= dstStartAdj)
  537. except ValueError:
  538. # there was an error parsing the time zone, which is normal when a
  539. # start and end time are not specified.
  540. in_dst = False
  541. return in_dst
  542. def GetDSTStartTime(self, year):
  543. "Given a year, determines the time when daylight savings time starts"
  544. return self.getWinInfo(year).locate_daylight_start(year)
  545. def GetDSTEndTime(self, year):
  546. "Given a year, determines the time when daylight savings ends."
  547. return self.getWinInfo(year).locate_standard_start(year)
  548. def __cmp__(self, other):
  549. return cmp(self.__dict__, other.__dict__)
  550. def __eq__(self, other):
  551. return self.__dict__ == other.__dict__
  552. def __ne__(self, other):
  553. return self.__dict__ != other.__dict__
  554. @classmethod
  555. def local(class_):
  556. """Returns the local time zone as defined by the operating system in the
  557. registry.
  558. >>> localTZ = TimeZoneInfo.local()
  559. >>> now_local = datetime.datetime.now(localTZ)
  560. >>> now_UTC = datetime.datetime.utcnow()
  561. >>> (now_UTC - now_local) < datetime.timedelta(seconds = 5)
  562. Traceback (most recent call last):
  563. ...
  564. TypeError: can't subtract offset-naive and offset-aware datetimes
  565. >>> now_UTC = now_UTC.replace(tzinfo = TimeZoneInfo('GMT Standard Time', True))
  566. Now one can compare the results of the two offset aware values
  567. >>> (now_UTC - now_local) < datetime.timedelta(seconds = 5)
  568. True
  569. """
  570. code, info = TimeZoneDefinition.current()
  571. # code is 0 if daylight savings is disabled or not defined
  572. # code is 1 or 2 if daylight savings is enabled, 2 if currently active
  573. fix_standard_time = not code
  574. # note that although the given information is sufficient
  575. # to construct a WinTZI object, it's
  576. # not sufficient to represent the time zone in which
  577. # the current user is operating due
  578. # to dynamic time zones.
  579. return class_(info, fix_standard_time)
  580. @classmethod
  581. def utc(class_):
  582. """Returns a time-zone representing UTC.
  583. Same as TimeZoneInfo('GMT Standard Time', True) but caches the result
  584. for performance.
  585. >>> isinstance(TimeZoneInfo.utc(), TimeZoneInfo)
  586. True
  587. """
  588. if '_tzutc' not in class_.__dict__:
  589. setattr(class_, '_tzutc', class_('GMT Standard Time', True))
  590. return class_._tzutc
  591. # helper methods for accessing the timezone info from the registry
  592. @staticmethod
  593. def _get_time_zone_key(subkey=None):
  594. "Return the registry key that stores time zone details"
  595. key = _RegKeyDict.open(
  596. winreg.HKEY_LOCAL_MACHINE, TimeZoneInfo.tzRegKey)
  597. if subkey:
  598. key = key.subkey(subkey)
  599. return key
  600. @staticmethod
  601. def _get_time_zone_key_names():
  602. "Returns the names of the (registry keys of the) time zones"
  603. return TimeZoneInfo._get_time_zone_key().subkeys()
  604. @staticmethod
  605. def _get_indexed_time_zone_keys(index_key='Index'):
  606. """
  607. Get the names of the registry keys indexed by a value in that key,
  608. ignoring any keys for which that value is empty or missing.
  609. """
  610. key_names = list(TimeZoneInfo._get_time_zone_key_names())
  611. def get_index_value(key_name):
  612. key = TimeZoneInfo._get_time_zone_key(key_name)
  613. return key.get(index_key)
  614. values = map(get_index_value, key_names)
  615. return (
  616. (value, key_name)
  617. for value, key_name in zip(values, key_names)
  618. if value
  619. )
  620. @staticmethod
  621. def get_sorted_time_zone_names():
  622. """
  623. Return a list of time zone names that can
  624. be used to initialize TimeZoneInfo instances.
  625. """
  626. tzs = TimeZoneInfo.get_sorted_time_zones()
  627. return [tz.standardName for tz in tzs]
  628. @staticmethod
  629. def get_all_time_zones():
  630. return [
  631. TimeZoneInfo(n) for n in TimeZoneInfo._get_time_zone_key_names()]
  632. @staticmethod
  633. def get_sorted_time_zones(key=None):
  634. """
  635. Return the time zones sorted by some key.
  636. key must be a function that takes a TimeZoneInfo object and returns
  637. a value suitable for sorting on.
  638. The key defaults to the bias (descending), as is done in Windows
  639. (see http://blogs.msdn.com/michkap/archive/2006/12/22/1350684.aspx)
  640. """
  641. key = key or (lambda tzi: -tzi.staticInfo.bias)
  642. zones = TimeZoneInfo.get_all_time_zones()
  643. zones.sort(key=key)
  644. return zones
  645. class _RegKeyDict(dict):
  646. def __init__(self, key):
  647. dict.__init__(self)
  648. self.key = key
  649. self.__load_values()
  650. @classmethod
  651. def open(cls, *args, **kargs):
  652. return _RegKeyDict(winreg.OpenKeyEx(*args, **kargs))
  653. def subkey(self, name):
  654. return _RegKeyDict(winreg.OpenKeyEx(self.key, name))
  655. def __load_values(self):
  656. pairs = [(n, v) for (n, v, t) in self._enumerate_reg_values(self.key)]
  657. self.update(pairs)
  658. def subkeys(self):
  659. return self._enumerate_reg_keys(self.key)
  660. @staticmethod
  661. def _enumerate_reg_values(key):
  662. return _RegKeyDict._enumerate_reg(key, winreg.EnumValue)
  663. @staticmethod
  664. def _enumerate_reg_keys(key):
  665. return _RegKeyDict._enumerate_reg(key, winreg.EnumKey)
  666. @staticmethod
  667. def _enumerate_reg(key, func):
  668. "Enumerates an open registry key as an iterable generator"
  669. try:
  670. for index in count():
  671. yield func(key, index)
  672. except WindowsError:
  673. pass
  674. def utcnow():
  675. """
  676. Return the UTC time now with timezone awareness as enabled
  677. by this module
  678. >>> now = utcnow()
  679. """
  680. now = datetime.datetime.utcnow()
  681. now = now.replace(tzinfo=TimeZoneInfo.utc())
  682. return now
  683. def now():
  684. """
  685. Return the local time now with timezone awareness as enabled
  686. by this module
  687. >>> now_local = now()
  688. """
  689. return datetime.datetime.now(TimeZoneInfo.local())
  690. def GetTZCapabilities():
  691. """
  692. Run a few known tests to determine the capabilities of
  693. the time zone database on this machine.
  694. Note Dynamic Time Zone support is not available on any
  695. platform at this time; this
  696. is a limitation of this library, not the platform."""
  697. tzi = TimeZoneInfo('Mountain Standard Time')
  698. MissingTZPatch = (
  699. datetime.datetime(2007, 11, 2, tzinfo=tzi).utctimetuple()
  700. != (2007, 11, 2, 6, 0, 0, 4, 306, 0)
  701. )
  702. DynamicTZSupport = (
  703. not MissingTZPatch
  704. and datetime.datetime(2003, 11, 2, tzinfo=tzi).utctimetuple()
  705. == (2003, 11, 2, 7, 0, 0, 6, 306, 0)
  706. )
  707. del tzi
  708. return locals()
  709. class DLLHandleCache(object):
  710. def __init__(self):
  711. self.__cache = {}
  712. def __getitem__(self, filename):
  713. key = filename.lower()
  714. return self.__cache.setdefault(key, win32api.LoadLibrary(key))
  715. DLLCache = DLLHandleCache()
  716. def resolveMUITimeZone(spec):
  717. """Resolve a multilingual user interface resource for the time zone name
  718. >>> #some pre-amble for the doc-tests to be py2k and py3k aware)
  719. >>> try: unicode and None
  720. ... except NameError: unicode=str
  721. ...
  722. >>> import sys
  723. >>> result = resolveMUITimeZone('@tzres.dll,-110')
  724. >>> expectedResultType = [type(None),unicode][sys.getwindowsversion() >= (6,)]
  725. >>> type(result) is expectedResultType
  726. True
  727. spec should be of the format @path,-stringID[;comment]
  728. see http://msdn2.microsoft.com/en-us/library/ms725481.aspx for details
  729. """
  730. pattern = re.compile(
  731. r'@(?P<dllname>.*),-(?P<index>\d+)(?:;(?P<comment>.*))?')
  732. matcher = pattern.match(spec)
  733. assert matcher, 'Could not parse MUI spec'
  734. try:
  735. handle = DLLCache[matcher.groupdict()['dllname']]
  736. result = win32api.LoadString(handle, int(matcher.groupdict()['index']))
  737. except win32api.error:
  738. result = None
  739. return result
  740. # from jaraco.util.dictlib 5.3.1
  741. class RangeMap(dict):
  742. """
  743. A dictionary-like object that uses the keys as bounds for a range.
  744. Inclusion of the value for that range is determined by the
  745. key_match_comparator, which defaults to less-than-or-equal.
  746. A value is returned for a key if it is the first key that matches in
  747. the sorted list of keys.
  748. One may supply keyword parameters to be passed to the sort function used
  749. to sort keys (i.e. cmp [python 2 only], keys, reverse) as sort_params.
  750. Let's create a map that maps 1-3 -> 'a', 4-6 -> 'b'
  751. >>> r = RangeMap({3: 'a', 6: 'b'}) # boy, that was easy
  752. >>> r[1], r[2], r[3], r[4], r[5], r[6]
  753. ('a', 'a', 'a', 'b', 'b', 'b')
  754. Even float values should work so long as the comparison operator
  755. supports it.
  756. >>> r[4.5]
  757. 'b'
  758. But you'll notice that the way rangemap is defined, it must be open-ended on one side.
  759. >>> r[0]
  760. 'a'
  761. >>> r[-1]
  762. 'a'
  763. One can close the open-end of the RangeMap by using undefined_value
  764. >>> r = RangeMap({0: RangeMap.undefined_value, 3: 'a', 6: 'b'})
  765. >>> r[0]
  766. Traceback (most recent call last):
  767. ...
  768. KeyError: 0
  769. One can get the first or last elements in the range by using RangeMap.Item
  770. >>> last_item = RangeMap.Item(-1)
  771. >>> r[last_item]
  772. 'b'
  773. .last_item is a shortcut for Item(-1)
  774. >>> r[RangeMap.last_item]
  775. 'b'
  776. Sometimes it's useful to find the bounds for a RangeMap
  777. >>> r.bounds()
  778. (0, 6)
  779. RangeMap supports .get(key, default)
  780. >>> r.get(0, 'not found')
  781. 'not found'
  782. >>> r.get(7, 'not found')
  783. 'not found'
  784. """
  785. def __init__(
  786. self, source, sort_params={}, key_match_comparator=operator.le):
  787. dict.__init__(self, source)
  788. self.sort_params = sort_params
  789. self.match = key_match_comparator
  790. def __getitem__(self, item):
  791. sorted_keys = sorted(list(self.keys()), **self.sort_params)
  792. if isinstance(item, RangeMap.Item):
  793. result = self.__getitem__(sorted_keys[item])
  794. else:
  795. key = self._find_first_match_(sorted_keys, item)
  796. result = dict.__getitem__(self, key)
  797. if result is RangeMap.undefined_value:
  798. raise KeyError(key)
  799. return result
  800. def get(self, key, default=None):
  801. """
  802. Return the value for key if key is in the dictionary, else default.
  803. If default is not given, it defaults to None, so that this method
  804. never raises a KeyError.
  805. """
  806. try:
  807. return self[key]
  808. except KeyError:
  809. return default
  810. def _find_first_match_(self, keys, item):
  811. def is_match(k):
  812. return self.match(item, k)
  813. matches = list(filter(is_match, keys))
  814. if matches:
  815. return matches[0]
  816. raise KeyError(item)
  817. def bounds(self):
  818. sorted_keys = sorted(list(self.keys()), **self.sort_params)
  819. return (
  820. sorted_keys[RangeMap.first_item],
  821. sorted_keys[RangeMap.last_item],
  822. )
  823. # some special values for the RangeMap
  824. undefined_value = type(str('RangeValueUndefined'), (object,), {})()
  825. class Item(int):
  826. pass
  827. first_item = Item(0)
  828. last_item = Item(-1)