python-dateutil 2.4.1__zip

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