tz.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986
  1. # -*- coding: utf-8 -*-
  2. """
  3. This module offers timezone implementations subclassing the abstract
  4. :py:`datetime.tzinfo` type. There are classes to handle tzfile format files
  5. (usually are in :file:`/etc/localtime`, :file:`/usr/share/zoneinfo`, etc), TZ
  6. environment string (in all known formats), given ranges (with help from
  7. relative deltas), local machine timezone, fixed offset timezone, and UTC
  8. timezone.
  9. """
  10. import datetime
  11. import struct
  12. import time
  13. import sys
  14. import os
  15. from six import string_types, PY3
  16. try:
  17. from dateutil.tzwin import tzwin, tzwinlocal
  18. except ImportError:
  19. tzwin = tzwinlocal = None
  20. relativedelta = None
  21. parser = None
  22. rrule = None
  23. __all__ = ["tzutc", "tzoffset", "tzlocal", "tzfile", "tzrange",
  24. "tzstr", "tzical", "tzwin", "tzwinlocal", "gettz"]
  25. def tzname_in_python2(myfunc):
  26. """Change unicode output into bytestrings in Python 2
  27. tzname() API changed in Python 3. It used to return bytes, but was changed
  28. to unicode strings
  29. """
  30. def inner_func(*args, **kwargs):
  31. if PY3:
  32. return myfunc(*args, **kwargs)
  33. else:
  34. return myfunc(*args, **kwargs).encode()
  35. return inner_func
  36. ZERO = datetime.timedelta(0)
  37. EPOCHORDINAL = datetime.datetime.utcfromtimestamp(0).toordinal()
  38. class tzutc(datetime.tzinfo):
  39. def utcoffset(self, dt):
  40. return ZERO
  41. def dst(self, dt):
  42. return ZERO
  43. @tzname_in_python2
  44. def tzname(self, dt):
  45. return "UTC"
  46. def __eq__(self, other):
  47. return (isinstance(other, tzutc) or
  48. (isinstance(other, tzoffset) and other._offset == ZERO))
  49. def __ne__(self, other):
  50. return not self.__eq__(other)
  51. def __repr__(self):
  52. return "%s()" % self.__class__.__name__
  53. __reduce__ = object.__reduce__
  54. class tzoffset(datetime.tzinfo):
  55. def __init__(self, name, offset):
  56. self._name = name
  57. self._offset = datetime.timedelta(seconds=offset)
  58. def utcoffset(self, dt):
  59. return self._offset
  60. def dst(self, dt):
  61. return ZERO
  62. @tzname_in_python2
  63. def tzname(self, dt):
  64. return self._name
  65. def __eq__(self, other):
  66. return (isinstance(other, tzoffset) and
  67. self._offset == other._offset)
  68. def __ne__(self, other):
  69. return not self.__eq__(other)
  70. def __repr__(self):
  71. return "%s(%s, %s)" % (self.__class__.__name__,
  72. repr(self._name),
  73. self._offset.days*86400+self._offset.seconds)
  74. __reduce__ = object.__reduce__
  75. class tzlocal(datetime.tzinfo):
  76. _std_offset = datetime.timedelta(seconds=-time.timezone)
  77. if time.daylight:
  78. _dst_offset = datetime.timedelta(seconds=-time.altzone)
  79. else:
  80. _dst_offset = _std_offset
  81. def utcoffset(self, dt):
  82. if self._isdst(dt):
  83. return self._dst_offset
  84. else:
  85. return self._std_offset
  86. def dst(self, dt):
  87. if self._isdst(dt):
  88. return self._dst_offset-self._std_offset
  89. else:
  90. return ZERO
  91. @tzname_in_python2
  92. def tzname(self, dt):
  93. return time.tzname[self._isdst(dt)]
  94. def _isdst(self, dt):
  95. # We can't use mktime here. It is unstable when deciding if
  96. # the hour near to a change is DST or not.
  97. #
  98. # timestamp = time.mktime((dt.year, dt.month, dt.day, dt.hour,
  99. # dt.minute, dt.second, dt.weekday(), 0, -1))
  100. # return time.localtime(timestamp).tm_isdst
  101. #
  102. # The code above yields the following result:
  103. #
  104. # >>> import tz, datetime
  105. # >>> t = tz.tzlocal()
  106. # >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname()
  107. # 'BRDT'
  108. # >>> datetime.datetime(2003,2,16,0,tzinfo=t).tzname()
  109. # 'BRST'
  110. # >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname()
  111. # 'BRST'
  112. # >>> datetime.datetime(2003,2,15,22,tzinfo=t).tzname()
  113. # 'BRDT'
  114. # >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname()
  115. # 'BRDT'
  116. #
  117. # Here is a more stable implementation:
  118. #
  119. timestamp = ((dt.toordinal() - EPOCHORDINAL) * 86400
  120. + dt.hour * 3600
  121. + dt.minute * 60
  122. + dt.second)
  123. return time.localtime(timestamp+time.timezone).tm_isdst
  124. def __eq__(self, other):
  125. if not isinstance(other, tzlocal):
  126. return False
  127. return (self._std_offset == other._std_offset and
  128. self._dst_offset == other._dst_offset)
  129. return True
  130. def __ne__(self, other):
  131. return not self.__eq__(other)
  132. def __repr__(self):
  133. return "%s()" % self.__class__.__name__
  134. __reduce__ = object.__reduce__
  135. class _ttinfo(object):
  136. __slots__ = ["offset", "delta", "isdst", "abbr", "isstd", "isgmt"]
  137. def __init__(self):
  138. for attr in self.__slots__:
  139. setattr(self, attr, None)
  140. def __repr__(self):
  141. l = []
  142. for attr in self.__slots__:
  143. value = getattr(self, attr)
  144. if value is not None:
  145. l.append("%s=%s" % (attr, repr(value)))
  146. return "%s(%s)" % (self.__class__.__name__, ", ".join(l))
  147. def __eq__(self, other):
  148. if not isinstance(other, _ttinfo):
  149. return False
  150. return (self.offset == other.offset and
  151. self.delta == other.delta and
  152. self.isdst == other.isdst and
  153. self.abbr == other.abbr and
  154. self.isstd == other.isstd and
  155. self.isgmt == other.isgmt)
  156. def __ne__(self, other):
  157. return not self.__eq__(other)
  158. def __getstate__(self):
  159. state = {}
  160. for name in self.__slots__:
  161. state[name] = getattr(self, name, None)
  162. return state
  163. def __setstate__(self, state):
  164. for name in self.__slots__:
  165. if name in state:
  166. setattr(self, name, state[name])
  167. class tzfile(datetime.tzinfo):
  168. # http://www.twinsun.com/tz/tz-link.htm
  169. # ftp://ftp.iana.org/tz/tz*.tar.gz
  170. def __init__(self, fileobj, filename=None):
  171. file_opened_here = False
  172. if isinstance(fileobj, string_types):
  173. self._filename = fileobj
  174. fileobj = open(fileobj, 'rb')
  175. file_opened_here = True
  176. elif filename is not None:
  177. self._filename = filename
  178. elif hasattr(fileobj, "name"):
  179. self._filename = fileobj.name
  180. else:
  181. self._filename = repr(fileobj)
  182. # From tzfile(5):
  183. #
  184. # The time zone information files used by tzset(3)
  185. # begin with the magic characters "TZif" to identify
  186. # them as time zone information files, followed by
  187. # sixteen bytes reserved for future use, followed by
  188. # six four-byte values of type long, written in a
  189. # ``standard'' byte order (the high-order byte
  190. # of the value is written first).
  191. try:
  192. if fileobj.read(4).decode() != "TZif":
  193. raise ValueError("magic not found")
  194. fileobj.read(16)
  195. (
  196. # The number of UTC/local indicators stored in the file.
  197. ttisgmtcnt,
  198. # The number of standard/wall indicators stored in the file.
  199. ttisstdcnt,
  200. # The number of leap seconds for which data is
  201. # stored in the file.
  202. leapcnt,
  203. # The number of "transition times" for which data
  204. # is stored in the file.
  205. timecnt,
  206. # The number of "local time types" for which data
  207. # is stored in the file (must not be zero).
  208. typecnt,
  209. # The number of characters of "time zone
  210. # abbreviation strings" stored in the file.
  211. charcnt,
  212. ) = struct.unpack(">6l", fileobj.read(24))
  213. # The above header is followed by tzh_timecnt four-byte
  214. # values of type long, sorted in ascending order.
  215. # These values are written in ``standard'' byte order.
  216. # Each is used as a transition time (as returned by
  217. # time(2)) at which the rules for computing local time
  218. # change.
  219. if timecnt:
  220. self._trans_list = struct.unpack(">%dl" % timecnt,
  221. fileobj.read(timecnt*4))
  222. else:
  223. self._trans_list = []
  224. # Next come tzh_timecnt one-byte values of type unsigned
  225. # char; each one tells which of the different types of
  226. # ``local time'' types described in the file is associated
  227. # with the same-indexed transition time. These values
  228. # serve as indices into an array of ttinfo structures that
  229. # appears next in the file.
  230. if timecnt:
  231. self._trans_idx = struct.unpack(">%dB" % timecnt,
  232. fileobj.read(timecnt))
  233. else:
  234. self._trans_idx = []
  235. # Each ttinfo structure is written as a four-byte value
  236. # for tt_gmtoff of type long, in a standard byte
  237. # order, followed by a one-byte value for tt_isdst
  238. # and a one-byte value for tt_abbrind. In each
  239. # structure, tt_gmtoff gives the number of
  240. # seconds to be added to UTC, tt_isdst tells whether
  241. # tm_isdst should be set by localtime(3), and
  242. # tt_abbrind serves as an index into the array of
  243. # time zone abbreviation characters that follow the
  244. # ttinfo structure(s) in the file.
  245. ttinfo = []
  246. for i in range(typecnt):
  247. ttinfo.append(struct.unpack(">lbb", fileobj.read(6)))
  248. abbr = fileobj.read(charcnt).decode()
  249. # Then there are tzh_leapcnt pairs of four-byte
  250. # values, written in standard byte order; the
  251. # first value of each pair gives the time (as
  252. # returned by time(2)) at which a leap second
  253. # occurs; the second gives the total number of
  254. # leap seconds to be applied after the given time.
  255. # The pairs of values are sorted in ascending order
  256. # by time.
  257. # Not used, for now
  258. # if leapcnt:
  259. # leap = struct.unpack(">%dl" % (leapcnt*2),
  260. # fileobj.read(leapcnt*8))
  261. # Then there are tzh_ttisstdcnt standard/wall
  262. # indicators, each stored as a one-byte value;
  263. # they tell whether the transition times associated
  264. # with local time types were specified as standard
  265. # time or wall clock time, and are used when
  266. # a time zone file is used in handling POSIX-style
  267. # time zone environment variables.
  268. if ttisstdcnt:
  269. isstd = struct.unpack(">%db" % ttisstdcnt,
  270. fileobj.read(ttisstdcnt))
  271. # Finally, there are tzh_ttisgmtcnt UTC/local
  272. # indicators, each stored as a one-byte value;
  273. # they tell whether the transition times associated
  274. # with local time types were specified as UTC or
  275. # local time, and are used when a time zone file
  276. # is used in handling POSIX-style time zone envi-
  277. # ronment variables.
  278. if ttisgmtcnt:
  279. isgmt = struct.unpack(">%db" % ttisgmtcnt,
  280. fileobj.read(ttisgmtcnt))
  281. # ** Everything has been read **
  282. finally:
  283. if file_opened_here:
  284. fileobj.close()
  285. # Build ttinfo list
  286. self._ttinfo_list = []
  287. for i in range(typecnt):
  288. gmtoff, isdst, abbrind = ttinfo[i]
  289. # Round to full-minutes if that's not the case. Python's
  290. # datetime doesn't accept sub-minute timezones. Check
  291. # http://python.org/sf/1447945 for some information.
  292. gmtoff = (gmtoff+30)//60*60
  293. tti = _ttinfo()
  294. tti.offset = gmtoff
  295. tti.delta = datetime.timedelta(seconds=gmtoff)
  296. tti.isdst = isdst
  297. tti.abbr = abbr[abbrind:abbr.find('\x00', abbrind)]
  298. tti.isstd = (ttisstdcnt > i and isstd[i] != 0)
  299. tti.isgmt = (ttisgmtcnt > i and isgmt[i] != 0)
  300. self._ttinfo_list.append(tti)
  301. # Replace ttinfo indexes for ttinfo objects.
  302. trans_idx = []
  303. for idx in self._trans_idx:
  304. trans_idx.append(self._ttinfo_list[idx])
  305. self._trans_idx = tuple(trans_idx)
  306. # Set standard, dst, and before ttinfos. before will be
  307. # used when a given time is before any transitions,
  308. # and will be set to the first non-dst ttinfo, or to
  309. # the first dst, if all of them are dst.
  310. self._ttinfo_std = None
  311. self._ttinfo_dst = None
  312. self._ttinfo_before = None
  313. if self._ttinfo_list:
  314. if not self._trans_list:
  315. self._ttinfo_std = self._ttinfo_first = self._ttinfo_list[0]
  316. else:
  317. for i in range(timecnt-1, -1, -1):
  318. tti = self._trans_idx[i]
  319. if not self._ttinfo_std and not tti.isdst:
  320. self._ttinfo_std = tti
  321. elif not self._ttinfo_dst and tti.isdst:
  322. self._ttinfo_dst = tti
  323. if self._ttinfo_std and self._ttinfo_dst:
  324. break
  325. else:
  326. if self._ttinfo_dst and not self._ttinfo_std:
  327. self._ttinfo_std = self._ttinfo_dst
  328. for tti in self._ttinfo_list:
  329. if not tti.isdst:
  330. self._ttinfo_before = tti
  331. break
  332. else:
  333. self._ttinfo_before = self._ttinfo_list[0]
  334. # Now fix transition times to become relative to wall time.
  335. #
  336. # I'm not sure about this. In my tests, the tz source file
  337. # is setup to wall time, and in the binary file isstd and
  338. # isgmt are off, so it should be in wall time. OTOH, it's
  339. # always in gmt time. Let me know if you have comments
  340. # about this.
  341. laststdoffset = 0
  342. self._trans_list = list(self._trans_list)
  343. for i in range(len(self._trans_list)):
  344. tti = self._trans_idx[i]
  345. if not tti.isdst:
  346. # This is std time.
  347. self._trans_list[i] += tti.offset
  348. laststdoffset = tti.offset
  349. else:
  350. # This is dst time. Convert to std.
  351. self._trans_list[i] += laststdoffset
  352. self._trans_list = tuple(self._trans_list)
  353. def _find_ttinfo(self, dt, laststd=0):
  354. timestamp = ((dt.toordinal() - EPOCHORDINAL) * 86400
  355. + dt.hour * 3600
  356. + dt.minute * 60
  357. + dt.second)
  358. idx = 0
  359. for trans in self._trans_list:
  360. if timestamp < trans:
  361. break
  362. idx += 1
  363. else:
  364. return self._ttinfo_std
  365. if idx == 0:
  366. return self._ttinfo_before
  367. if laststd:
  368. while idx > 0:
  369. tti = self._trans_idx[idx-1]
  370. if not tti.isdst:
  371. return tti
  372. idx -= 1
  373. else:
  374. return self._ttinfo_std
  375. else:
  376. return self._trans_idx[idx-1]
  377. def utcoffset(self, dt):
  378. if not self._ttinfo_std:
  379. return ZERO
  380. return self._find_ttinfo(dt).delta
  381. def dst(self, dt):
  382. if not self._ttinfo_dst:
  383. return ZERO
  384. tti = self._find_ttinfo(dt)
  385. if not tti.isdst:
  386. return ZERO
  387. # The documentation says that utcoffset()-dst() must
  388. # be constant for every dt.
  389. return tti.delta-self._find_ttinfo(dt, laststd=1).delta
  390. # An alternative for that would be:
  391. #
  392. # return self._ttinfo_dst.offset-self._ttinfo_std.offset
  393. #
  394. # However, this class stores historical changes in the
  395. # dst offset, so I belive that this wouldn't be the right
  396. # way to implement this.
  397. @tzname_in_python2
  398. def tzname(self, dt):
  399. if not self._ttinfo_std:
  400. return None
  401. return self._find_ttinfo(dt).abbr
  402. def __eq__(self, other):
  403. if not isinstance(other, tzfile):
  404. return False
  405. return (self._trans_list == other._trans_list and
  406. self._trans_idx == other._trans_idx and
  407. self._ttinfo_list == other._ttinfo_list)
  408. def __ne__(self, other):
  409. return not self.__eq__(other)
  410. def __repr__(self):
  411. return "%s(%s)" % (self.__class__.__name__, repr(self._filename))
  412. def __reduce__(self):
  413. if not os.path.isfile(self._filename):
  414. raise ValueError("Unpickable %s class" % self.__class__.__name__)
  415. return (self.__class__, (self._filename,))
  416. class tzrange(datetime.tzinfo):
  417. def __init__(self, stdabbr, stdoffset=None,
  418. dstabbr=None, dstoffset=None,
  419. start=None, end=None):
  420. global relativedelta
  421. if not relativedelta:
  422. from dateutil import relativedelta
  423. self._std_abbr = stdabbr
  424. self._dst_abbr = dstabbr
  425. if stdoffset is not None:
  426. self._std_offset = datetime.timedelta(seconds=stdoffset)
  427. else:
  428. self._std_offset = ZERO
  429. if dstoffset is not None:
  430. self._dst_offset = datetime.timedelta(seconds=dstoffset)
  431. elif dstabbr and stdoffset is not None:
  432. self._dst_offset = self._std_offset+datetime.timedelta(hours=+1)
  433. else:
  434. self._dst_offset = ZERO
  435. if dstabbr and start is None:
  436. self._start_delta = relativedelta.relativedelta(
  437. hours=+2, month=4, day=1, weekday=relativedelta.SU(+1))
  438. else:
  439. self._start_delta = start
  440. if dstabbr and end is None:
  441. self._end_delta = relativedelta.relativedelta(
  442. hours=+1, month=10, day=31, weekday=relativedelta.SU(-1))
  443. else:
  444. self._end_delta = end
  445. def utcoffset(self, dt):
  446. if self._isdst(dt):
  447. return self._dst_offset
  448. else:
  449. return self._std_offset
  450. def dst(self, dt):
  451. if self._isdst(dt):
  452. return self._dst_offset-self._std_offset
  453. else:
  454. return ZERO
  455. @tzname_in_python2
  456. def tzname(self, dt):
  457. if self._isdst(dt):
  458. return self._dst_abbr
  459. else:
  460. return self._std_abbr
  461. def _isdst(self, dt):
  462. if not self._start_delta:
  463. return False
  464. year = datetime.datetime(dt.year, 1, 1)
  465. start = year+self._start_delta
  466. end = year+self._end_delta
  467. dt = dt.replace(tzinfo=None)
  468. if start < end:
  469. return dt >= start and dt < end
  470. else:
  471. return dt >= start or dt < end
  472. def __eq__(self, other):
  473. if not isinstance(other, tzrange):
  474. return False
  475. return (self._std_abbr == other._std_abbr and
  476. self._dst_abbr == other._dst_abbr and
  477. self._std_offset == other._std_offset and
  478. self._dst_offset == other._dst_offset and
  479. self._start_delta == other._start_delta and
  480. self._end_delta == other._end_delta)
  481. def __ne__(self, other):
  482. return not self.__eq__(other)
  483. def __repr__(self):
  484. return "%s(...)" % self.__class__.__name__
  485. __reduce__ = object.__reduce__
  486. class tzstr(tzrange):
  487. def __init__(self, s):
  488. global parser
  489. if not parser:
  490. from dateutil import parser
  491. self._s = s
  492. res = parser._parsetz(s)
  493. if res is None:
  494. raise ValueError("unknown string format")
  495. # Here we break the compatibility with the TZ variable handling.
  496. # GMT-3 actually *means* the timezone -3.
  497. if res.stdabbr in ("GMT", "UTC"):
  498. res.stdoffset *= -1
  499. # We must initialize it first, since _delta() needs
  500. # _std_offset and _dst_offset set. Use False in start/end
  501. # to avoid building it two times.
  502. tzrange.__init__(self, res.stdabbr, res.stdoffset,
  503. res.dstabbr, res.dstoffset,
  504. start=False, end=False)
  505. if not res.dstabbr:
  506. self._start_delta = None
  507. self._end_delta = None
  508. else:
  509. self._start_delta = self._delta(res.start)
  510. if self._start_delta:
  511. self._end_delta = self._delta(res.end, isend=1)
  512. def _delta(self, x, isend=0):
  513. kwargs = {}
  514. if x.month is not None:
  515. kwargs["month"] = x.month
  516. if x.weekday is not None:
  517. kwargs["weekday"] = relativedelta.weekday(x.weekday, x.week)
  518. if x.week > 0:
  519. kwargs["day"] = 1
  520. else:
  521. kwargs["day"] = 31
  522. elif x.day:
  523. kwargs["day"] = x.day
  524. elif x.yday is not None:
  525. kwargs["yearday"] = x.yday
  526. elif x.jyday is not None:
  527. kwargs["nlyearday"] = x.jyday
  528. if not kwargs:
  529. # Default is to start on first sunday of april, and end
  530. # on last sunday of october.
  531. if not isend:
  532. kwargs["month"] = 4
  533. kwargs["day"] = 1
  534. kwargs["weekday"] = relativedelta.SU(+1)
  535. else:
  536. kwargs["month"] = 10
  537. kwargs["day"] = 31
  538. kwargs["weekday"] = relativedelta.SU(-1)
  539. if x.time is not None:
  540. kwargs["seconds"] = x.time
  541. else:
  542. # Default is 2AM.
  543. kwargs["seconds"] = 7200
  544. if isend:
  545. # Convert to standard time, to follow the documented way
  546. # of working with the extra hour. See the documentation
  547. # of the tzinfo class.
  548. delta = self._dst_offset-self._std_offset
  549. kwargs["seconds"] -= delta.seconds+delta.days*86400
  550. return relativedelta.relativedelta(**kwargs)
  551. def __repr__(self):
  552. return "%s(%s)" % (self.__class__.__name__, repr(self._s))
  553. class _tzicalvtzcomp(object):
  554. def __init__(self, tzoffsetfrom, tzoffsetto, isdst,
  555. tzname=None, rrule=None):
  556. self.tzoffsetfrom = datetime.timedelta(seconds=tzoffsetfrom)
  557. self.tzoffsetto = datetime.timedelta(seconds=tzoffsetto)
  558. self.tzoffsetdiff = self.tzoffsetto-self.tzoffsetfrom
  559. self.isdst = isdst
  560. self.tzname = tzname
  561. self.rrule = rrule
  562. class _tzicalvtz(datetime.tzinfo):
  563. def __init__(self, tzid, comps=[]):
  564. self._tzid = tzid
  565. self._comps = comps
  566. self._cachedate = []
  567. self._cachecomp = []
  568. def _find_comp(self, dt):
  569. if len(self._comps) == 1:
  570. return self._comps[0]
  571. dt = dt.replace(tzinfo=None)
  572. try:
  573. return self._cachecomp[self._cachedate.index(dt)]
  574. except ValueError:
  575. pass
  576. lastcomp = None
  577. lastcompdt = None
  578. for comp in self._comps:
  579. if not comp.isdst:
  580. # Handle the extra hour in DST -> STD
  581. compdt = comp.rrule.before(dt-comp.tzoffsetdiff, inc=True)
  582. else:
  583. compdt = comp.rrule.before(dt, inc=True)
  584. if compdt and (not lastcompdt or lastcompdt < compdt):
  585. lastcompdt = compdt
  586. lastcomp = comp
  587. if not lastcomp:
  588. # RFC says nothing about what to do when a given
  589. # time is before the first onset date. We'll look for the
  590. # first standard component, or the first component, if
  591. # none is found.
  592. for comp in self._comps:
  593. if not comp.isdst:
  594. lastcomp = comp
  595. break
  596. else:
  597. lastcomp = comp[0]
  598. self._cachedate.insert(0, dt)
  599. self._cachecomp.insert(0, lastcomp)
  600. if len(self._cachedate) > 10:
  601. self._cachedate.pop()
  602. self._cachecomp.pop()
  603. return lastcomp
  604. def utcoffset(self, dt):
  605. return self._find_comp(dt).tzoffsetto
  606. def dst(self, dt):
  607. comp = self._find_comp(dt)
  608. if comp.isdst:
  609. return comp.tzoffsetdiff
  610. else:
  611. return ZERO
  612. @tzname_in_python2
  613. def tzname(self, dt):
  614. return self._find_comp(dt).tzname
  615. def __repr__(self):
  616. return "<tzicalvtz %s>" % repr(self._tzid)
  617. __reduce__ = object.__reduce__
  618. class tzical(object):
  619. def __init__(self, fileobj):
  620. global rrule
  621. if not rrule:
  622. from dateutil import rrule
  623. if isinstance(fileobj, string_types):
  624. self._s = fileobj
  625. # ical should be encoded in UTF-8 with CRLF
  626. fileobj = open(fileobj, 'r')
  627. elif hasattr(fileobj, "name"):
  628. self._s = fileobj.name
  629. else:
  630. self._s = repr(fileobj)
  631. self._vtz = {}
  632. self._parse_rfc(fileobj.read())
  633. def keys(self):
  634. return list(self._vtz.keys())
  635. def get(self, tzid=None):
  636. if tzid is None:
  637. keys = list(self._vtz.keys())
  638. if len(keys) == 0:
  639. raise ValueError("no timezones defined")
  640. elif len(keys) > 1:
  641. raise ValueError("more than one timezone available")
  642. tzid = keys[0]
  643. return self._vtz.get(tzid)
  644. def _parse_offset(self, s):
  645. s = s.strip()
  646. if not s:
  647. raise ValueError("empty offset")
  648. if s[0] in ('+', '-'):
  649. signal = (-1, +1)[s[0] == '+']
  650. s = s[1:]
  651. else:
  652. signal = +1
  653. if len(s) == 4:
  654. return (int(s[:2])*3600+int(s[2:])*60)*signal
  655. elif len(s) == 6:
  656. return (int(s[:2])*3600+int(s[2:4])*60+int(s[4:]))*signal
  657. else:
  658. raise ValueError("invalid offset: "+s)
  659. def _parse_rfc(self, s):
  660. lines = s.splitlines()
  661. if not lines:
  662. raise ValueError("empty string")
  663. # Unfold
  664. i = 0
  665. while i < len(lines):
  666. line = lines[i].rstrip()
  667. if not line:
  668. del lines[i]
  669. elif i > 0 and line[0] == " ":
  670. lines[i-1] += line[1:]
  671. del lines[i]
  672. else:
  673. i += 1
  674. tzid = None
  675. comps = []
  676. invtz = False
  677. comptype = None
  678. for line in lines:
  679. if not line:
  680. continue
  681. name, value = line.split(':', 1)
  682. parms = name.split(';')
  683. if not parms:
  684. raise ValueError("empty property name")
  685. name = parms[0].upper()
  686. parms = parms[1:]
  687. if invtz:
  688. if name == "BEGIN":
  689. if value in ("STANDARD", "DAYLIGHT"):
  690. # Process component
  691. pass
  692. else:
  693. raise ValueError("unknown component: "+value)
  694. comptype = value
  695. founddtstart = False
  696. tzoffsetfrom = None
  697. tzoffsetto = None
  698. rrulelines = []
  699. tzname = None
  700. elif name == "END":
  701. if value == "VTIMEZONE":
  702. if comptype:
  703. raise ValueError("component not closed: "+comptype)
  704. if not tzid:
  705. raise ValueError("mandatory TZID not found")
  706. if not comps:
  707. raise ValueError(
  708. "at least one component is needed")
  709. # Process vtimezone
  710. self._vtz[tzid] = _tzicalvtz(tzid, comps)
  711. invtz = False
  712. elif value == comptype:
  713. if not founddtstart:
  714. raise ValueError("mandatory DTSTART not found")
  715. if tzoffsetfrom is None:
  716. raise ValueError(
  717. "mandatory TZOFFSETFROM not found")
  718. if tzoffsetto is None:
  719. raise ValueError(
  720. "mandatory TZOFFSETFROM not found")
  721. # Process component
  722. rr = None
  723. if rrulelines:
  724. rr = rrule.rrulestr("\n".join(rrulelines),
  725. compatible=True,
  726. ignoretz=True,
  727. cache=True)
  728. comp = _tzicalvtzcomp(tzoffsetfrom, tzoffsetto,
  729. (comptype == "DAYLIGHT"),
  730. tzname, rr)
  731. comps.append(comp)
  732. comptype = None
  733. else:
  734. raise ValueError("invalid component end: "+value)
  735. elif comptype:
  736. if name == "DTSTART":
  737. rrulelines.append(line)
  738. founddtstart = True
  739. elif name in ("RRULE", "RDATE", "EXRULE", "EXDATE"):
  740. rrulelines.append(line)
  741. elif name == "TZOFFSETFROM":
  742. if parms:
  743. raise ValueError(
  744. "unsupported %s parm: %s " % (name, parms[0]))
  745. tzoffsetfrom = self._parse_offset(value)
  746. elif name == "TZOFFSETTO":
  747. if parms:
  748. raise ValueError(
  749. "unsupported TZOFFSETTO parm: "+parms[0])
  750. tzoffsetto = self._parse_offset(value)
  751. elif name == "TZNAME":
  752. if parms:
  753. raise ValueError(
  754. "unsupported TZNAME parm: "+parms[0])
  755. tzname = value
  756. elif name == "COMMENT":
  757. pass
  758. else:
  759. raise ValueError("unsupported property: "+name)
  760. else:
  761. if name == "TZID":
  762. if parms:
  763. raise ValueError(
  764. "unsupported TZID parm: "+parms[0])
  765. tzid = value
  766. elif name in ("TZURL", "LAST-MODIFIED", "COMMENT"):
  767. pass
  768. else:
  769. raise ValueError("unsupported property: "+name)
  770. elif name == "BEGIN" and value == "VTIMEZONE":
  771. tzid = None
  772. comps = []
  773. invtz = True
  774. def __repr__(self):
  775. return "%s(%s)" % (self.__class__.__name__, repr(self._s))
  776. if sys.platform != "win32":
  777. TZFILES = ["/etc/localtime", "localtime"]
  778. TZPATHS = ["/usr/share/zoneinfo", "/usr/lib/zoneinfo", "/etc/zoneinfo"]
  779. else:
  780. TZFILES = []
  781. TZPATHS = []
  782. def gettz(name=None):
  783. tz = None
  784. if not name:
  785. try:
  786. name = os.environ["TZ"]
  787. except KeyError:
  788. pass
  789. if name is None or name == ":":
  790. for filepath in TZFILES:
  791. if not os.path.isabs(filepath):
  792. filename = filepath
  793. for path in TZPATHS:
  794. filepath = os.path.join(path, filename)
  795. if os.path.isfile(filepath):
  796. break
  797. else:
  798. continue
  799. if os.path.isfile(filepath):
  800. try:
  801. tz = tzfile(filepath)
  802. break
  803. except (IOError, OSError, ValueError):
  804. pass
  805. else:
  806. tz = tzlocal()
  807. else:
  808. if name.startswith(":"):
  809. name = name[:-1]
  810. if os.path.isabs(name):
  811. if os.path.isfile(name):
  812. tz = tzfile(name)
  813. else:
  814. tz = None
  815. else:
  816. for path in TZPATHS:
  817. filepath = os.path.join(path, name)
  818. if not os.path.isfile(filepath):
  819. filepath = filepath.replace(' ', '_')
  820. if not os.path.isfile(filepath):
  821. continue
  822. try:
  823. tz = tzfile(filepath)
  824. break
  825. except (IOError, OSError, ValueError):
  826. pass
  827. else:
  828. tz = None
  829. if tzwin is not None:
  830. try:
  831. tz = tzwin(name)
  832. except WindowsError:
  833. tz = None
  834. if not tz:
  835. from dateutil.zoneinfo import gettz
  836. tz = gettz(name)
  837. if not tz:
  838. for c in name:
  839. # name must have at least one offset to be a tzstr
  840. if c in "0123456789":
  841. try:
  842. tz = tzstr(name)
  843. except ValueError:
  844. pass
  845. break
  846. else:
  847. if name in ("GMT", "UTC"):
  848. tz = tzutc()
  849. elif name in time.tzname:
  850. tz = tzlocal()
  851. return tz
  852. # vim:ts=4:sw=4:et