pep8 and style modifications
diff --git a/dateutil/easter.py b/dateutil/easter.py
index 00fad99..8d30c4e 100644
--- a/dateutil/easter.py
+++ b/dateutil/easter.py
@@ -8,9 +8,10 @@
__all__ = ["easter", "EASTER_JULIAN", "EASTER_ORTHODOX", "EASTER_WESTERN"]
-EASTER_JULIAN = 1
+EASTER_JULIAN = 1
EASTER_ORTHODOX = 2
-EASTER_WESTERN = 3
+EASTER_WESTERN = 3
+
def easter(year, method=EASTER_WESTERN):
"""
@@ -66,24 +67,23 @@
e = 0
if method < 3:
# Old method
- i = (19*g+15)%30
- j = (y+y//4+i)%7
+ i = (19*g + 15) % 30
+ j = (y + y//4 + i) % 7
if method == 2:
# Extra dates to convert Julian to Gregorian date
e = 10
if y > 1600:
- e = e+y//100-16-(y//100-16)//4
+ e = e + y//100 - 16 - (y//100 - 16)//4
else:
# New method
c = y//100
- h = (c-c//4-(8*c+13)//25+19*g+15)%30
- i = h-(h//28)*(1-(h//28)*(29//(h+1))*((21-g)//11))
- j = (y+y//4+i+2-c+c//4)%7
+ h = (c - c//4 - (8*c + 13)//25 + 19*g + 15) % 30
+ i = h - (h//28)*(1 - (h//28)*(29//(h + 1))*((21 - g)//11))
+ j = (y + y//4 + i + 2 - c + c//4) % 7
# p can be from -6 to 56 corresponding to dates 22 March to 23 May
# (later dates apply to method 2, although 23 May never actually occurs)
- p = i-j+e
- d = 1+(p+27+(p+6)//40)%31
- m = 3+(p+26)//30
+ p = i - j + e
+ d = 1 + (p + 27 + (p + 6)//40) % 31
+ m = 3 + (p + 26)//30
return datetime.date(int(y), int(m), int(d))
-
diff --git a/dateutil/parser.py b/dateutil/parser.py
index ade34b9..8b6c2d2 100644
--- a/dateutil/parser.py
+++ b/dateutil/parser.py
@@ -8,8 +8,6 @@
import datetime
import string
import time
-import sys
-import os
import collections
from io import StringIO
@@ -74,9 +72,9 @@
state = '0'
elif nextchar in whitespace:
token = ' '
- break # emit token
+ break # emit token
else:
- break # emit token
+ break # emit token
elif state == 'a':
seenletters = True
if nextchar in wordchars:
@@ -86,7 +84,7 @@
state = 'a.'
else:
self.charstack.append(nextchar)
- break # emit token
+ break # emit token
elif state == '0':
if nextchar in numchars:
token += nextchar
@@ -95,7 +93,7 @@
state = '0.'
else:
self.charstack.append(nextchar)
- break # emit token
+ break # emit token
elif state == 'a.':
seenletters = True
if nextchar == '.' or nextchar in wordchars:
@@ -105,7 +103,7 @@
state = '0.'
else:
self.charstack.append(nextchar)
- break # emit token
+ break # emit token
elif state == '0.':
if nextchar == '.' or nextchar in numchars:
token += nextchar
@@ -114,9 +112,9 @@
state = 'a.'
else:
self.charstack.append(nextchar)
- break # emit token
- if (state in ('a.', '0.') and
- (seenletters or token.count('.') > 1 or token[-1] == '.')):
+ break # emit token
+ if (state in ('a.', '0.') and (seenletters or token.count('.') > 1 or
+ token[-1] == '.')):
l = token.split('.')
token = l[0]
for tok in l[1:]:
@@ -174,18 +172,18 @@
("Fri", "Friday"),
("Sat", "Saturday"),
("Sun", "Sunday")]
- MONTHS = [("Jan", "January"),
- ("Feb", "February"),
- ("Mar", "March"),
- ("Apr", "April"),
- ("May", "May"),
- ("Jun", "June"),
- ("Jul", "July"),
- ("Aug", "August"),
- ("Sep", "Sept", "September"),
- ("Oct", "October"),
- ("Nov", "November"),
- ("Dec", "December")]
+ MONTHS = [("Jan", "January"),
+ ("Feb", "February"),
+ ("Mar", "March"),
+ ("Apr", "April"),
+ ("May", "May"),
+ ("Jun", "June"),
+ ("Jul", "July"),
+ ("Aug", "August"),
+ ("Sep", "Sept", "September"),
+ ("Oct", "October"),
+ ("Nov", "November"),
+ ("Dec", "December")]
HMS = [("h", "hour", "hours"),
("m", "minute", "minutes"),
("s", "second", "seconds")]
@@ -290,17 +288,16 @@
def __init__(self, info=None):
self.info = info or parserinfo()
- def parse(self, timestr, default=None,
- ignoretz=False, tzinfos=None,
- **kwargs):
+ def parse(self, timestr, default=None, ignoretz=False, tzinfos=None,
+ **kwargs):
if not default:
default = datetime.datetime.now().replace(hour=0, minute=0,
second=0, microsecond=0)
- if kwargs.get('fuzzy_with_tokens',False):
+ if kwargs.get('fuzzy_with_tokens', False):
res, skipped_tokens = self._parse(timestr, **kwargs)
else:
- res = self._parse(timestr,**kwargs)
+ res = self._parse(timestr, **kwargs)
if res is None:
raise ValueError("unknown string format")
@@ -314,7 +311,8 @@
if res.weekday is not None and not res.day:
ret = ret+relativedelta.relativedelta(weekday=res.weekday)
if not ignoretz:
- if isinstance(tzinfos, collections.Callable) or tzinfos and res.tzname in tzinfos:
+ if (isinstance(tzinfos, collections.Callable) or
+ tzinfos and res.tzname in tzinfos):
if isinstance(tzinfos, collections.Callable):
tzdata = tzinfos(res.tzname, res.tzoffset)
else:
@@ -326,8 +324,8 @@
elif isinstance(tzdata, integer_types):
tzinfo = tz.tzoffset(res.tzname, tzdata)
else:
- raise ValueError("offset must be tzinfo subclass, " \
- "tz string, or int offset")
+ raise ValueError("offset must be tzinfo subclass, "
+ "tz string, or int offset")
ret = ret.replace(tzinfo=tzinfo)
elif res.tzname and res.tzname in time.tzname:
ret = ret.replace(tzinfo=tz.tzlocal())
@@ -336,7 +334,7 @@
elif res.tzoffset:
ret = ret.replace(tzinfo=tz.tzoffset(res.tzname, res.tzoffset))
- if kwargs.get('fuzzy_with_tokens',False):
+ if kwargs.get('fuzzy_with_tokens', False):
return ret, skipped_tokens
else:
return ret
@@ -346,7 +344,8 @@
"hour", "minute", "second", "microsecond",
"tzname", "tzoffset"]
- def _parse(self, timestr, dayfirst=None, yearfirst=None, fuzzy=False, fuzzy_with_tokens=False):
+ def _parse(self, timestr, dayfirst=None, yearfirst=None, fuzzy=False,
+ fuzzy_with_tokens=False):
if fuzzy_with_tokens:
fuzzy = True
@@ -358,7 +357,6 @@
res = self._result()
l = _timelex.split(timestr)
-
# keep up with the last token skipped so we can recombine
# consecutively skipped tokens (-2 for when i begins at 0).
last_skipped_token_i = -2
@@ -433,12 +431,12 @@
while True:
if idx == 0:
res.hour = int(value)
- if value%1:
- res.minute = int(60*(value%1))
+ if value % 1:
+ res.minute = int(60*(value % 1))
elif idx == 1:
res.minute = int(value)
- if value%1:
- res.second = int(60*(value%1))
+ if value % 1:
+ res.second = int(60*(value % 1))
elif idx == 2:
res.second, res.microsecond = \
_parsems(value_repr)
@@ -458,16 +456,17 @@
newidx = info.hms(l[i])
if newidx is not None:
idx = newidx
- elif i == len_l and l[i-2] == ' ' and info.hms(l[i-3]) is not None:
+ elif (i == len_l and l[i-2] == ' ' and
+ info.hms(l[i-3]) is not None):
# X h MM or X m SS
idx = info.hms(l[i-3]) + 1
if idx == 1:
res.minute = int(value)
- if value%1:
- res.second = int(60*(value%1))
+ if value % 1:
+ res.second = int(60*(value % 1))
elif idx == 2:
res.second, res.microsecond = \
- _parsems(value_repr)
+ _parsems(value_repr)
i += 1
elif i+1 < len_l and l[i] == ':':
# HH:MM[:SS[.ss]]
@@ -475,8 +474,8 @@
i += 1
value = float(l[i])
res.minute = int(value)
- if value%1:
- res.second = int(60*(value%1))
+ if value % 1:
+ res.second = int(60*(value % 1))
i += 1
if i < len_l and l[i] == ':':
res.second, res.microsecond = _parsems(l[i+1])
@@ -590,8 +589,9 @@
# Check for a timezone name
if (res.hour is not None and len(l[i]) <= 5 and
- res.tzname is None and res.tzoffset is None and
- not [x for x in l[i] if x not in string.ascii_uppercase]):
+ res.tzname is None and res.tzoffset is None and
+ not [x for x in l[i] if x not in
+ string.ascii_uppercase]):
res.tzname = l[i]
res.tzoffset = info.tzoffset(res.tzname)
i += 1
@@ -636,7 +636,7 @@
info.jump(l[i]) and l[i+1] == '(' and l[i+3] == ')' and
3 <= len(l[i+2]) <= 5 and
not [x for x in l[i+2]
- if x not in string.ascii_uppercase]):
+ if x not in string.ascii_uppercase]):
# -0300 (BRST)
res.tzname = l[i+2]
i += 4
@@ -729,6 +729,8 @@
return res
DEFAULTPARSER = parser()
+
+
def parse(timestr, parserinfo=None, **kwargs):
# Python 2.x support: datetimes return their string presentation as
# bytes in 2.x and unicode in 3.x, so it's reasonable to expect that
@@ -772,7 +774,7 @@
# BRST+3[BRDT[+2]]
j = i
while j < len_l and not [x for x in l[j]
- if x in "0123456789:,-+"]:
+ if x in "0123456789:,-+"]:
j += 1
if j != i:
if not res.stdabbr:
@@ -782,8 +784,8 @@
offattr = "dstoffset"
res.dstabbr = "".join(l[i:j])
i = j
- if (i < len_l and
- (l[i] in ('+', '-') or l[i][0] in "0123456789")):
+ if (i < len_l and (l[i] in ('+', '-') or l[i][0] in
+ "0123456789")):
if l[i] in ('+', '-'):
# Yes, that's right. See the TZ variable
# documentation.
@@ -794,8 +796,8 @@
len_li = len(l[i])
if len_li == 4:
# -0300
- setattr(res, offattr,
- (int(l[i][:2])*3600+int(l[i][2:])*60)*signal)
+ setattr(res, offattr, (int(l[i][:2])*3600 +
+ int(l[i][2:])*60)*signal)
elif i+1 < len_l and l[i+1] == ':':
# -03:00
setattr(res, offattr,
@@ -815,7 +817,8 @@
if i < len_l:
for j in range(i, len_l):
- if l[j] == ';': l[j] = ','
+ if l[j] == ';':
+ l[j] = ','
assert l[i] == ','
@@ -824,7 +827,7 @@
if i >= len_l:
pass
elif (8 <= l.count(',') <= 9 and
- not [y for x in l[i:] if x != ','
+ not [y for x in l[i:] if x != ','
for y in x if y not in "0123456789"]):
# GMT0BST,3,0,30,3600,10,0,26,7200[,3600]
for x in (res.start, res.end):
@@ -838,7 +841,7 @@
i += 2
if value:
x.week = value
- x.weekday = (int(l[i])-1)%7
+ x.weekday = (int(l[i])-1) % 7
else:
x.day = int(l[i])
i += 2
@@ -854,7 +857,7 @@
elif (l.count(',') == 2 and l[i:].count('/') <= 2 and
not [y for x in l[i:] if x not in (',', '/', 'J', 'M',
'.', '-', ':')
- for y in x if y not in "0123456789"]):
+ for y in x if y not in "0123456789"]):
for x in (res.start, res.end):
if l[i] == 'J':
# non-leap year day (1 based)
@@ -873,7 +876,7 @@
i += 1
assert l[i] in ('-', '.')
i += 1
- x.weekday = (int(l[i])-1)%7
+ x.weekday = (int(l[i])-1) % 7
else:
# year day (zero based)
x.yday = int(l[i])+1
@@ -914,6 +917,8 @@
DEFAULTTZPARSER = _tzparser()
+
+
def _parsetz(tzstr):
return DEFAULTTZPARSER.parse(tzstr)
diff --git a/dateutil/relativedelta.py b/dateutil/relativedelta.py
index 213ec0b..9819c5e 100644
--- a/dateutil/relativedelta.py
+++ b/dateutil/relativedelta.py
@@ -6,6 +6,7 @@
__all__ = ["relativedelta", "MO", "TU", "WE", "TH", "FR", "SA", "SU"]
+
class weekday(object):
__slots__ = ["weekday", "n"]
@@ -36,12 +37,13 @@
MO, TU, WE, TH, FR, SA, SU = weekdays = tuple([weekday(x) for x in range(7)])
+
class relativedelta(object):
"""
The relativedelta type is based on the specification of the excelent
work done by M.-A. Lemburg in his
-`mx.DateTime <http://www.egenix.com/files/python/mxDateTime.html>`_ extension. However,
-notice that this type does *NOT* implement the same algorithm as
+`mx.DateTime <http://www.egenix.com/files/python/mxDateTime.html>`_ extension.
+However, notice that this type does *NOT* implement the same algorithm as
his work. Do *NOT* expect it to behave like mx.DateTime's counterpart.
There's two different ways to build a relativedelta instance. The
@@ -108,9 +110,10 @@
yearday=None, nlyearday=None,
hour=None, minute=None, second=None, microsecond=None):
if dt1 and dt2:
- if (not isinstance(dt1, datetime.date)) or (not isinstance(dt2, datetime.date)):
+ if not (isinstance(dt1, datetime.date) and
+ isinstance(dt2, datetime.date)):
raise TypeError("relativedelta only diffs datetime/date")
- if not type(dt1) == type(dt2): #isinstance(dt1, type(dt2)):
+ if not type(dt1) == type(dt2):
if not isinstance(dt1, datetime.datetime):
dt1 = datetime.datetime.fromordinal(dt1.toordinal())
elif not isinstance(dt2, datetime.datetime):
@@ -179,7 +182,8 @@
if yearday > 59:
self.leapdays = -1
if yday:
- ydayidx = [31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 366]
+ ydayidx = [31, 59, 90, 120, 151, 181, 212,
+ 243, 273, 304, 334, 366]
for idx, ydays in enumerate(ydayidx):
if yday <= ydays:
self.month = idx+1
@@ -219,9 +223,9 @@
div, mod = divmod(self.months*s, 12)
self.months = mod*s
self.years += div*s
- if (self.hours or self.minutes or self.seconds or self.microseconds or
- self.hour is not None or self.minute is not None or
- self.second is not None or self.microsecond is not None):
+ if (self.hours or self.minutes or self.seconds or self.microseconds
+ or self.hour is not None or self.minute is not None or
+ self.second is not None or self.microsecond is not None):
self._has_time = 1
else:
self._has_time = 0
@@ -239,21 +243,23 @@
def __add__(self, other):
if isinstance(other, relativedelta):
return relativedelta(years=other.years+self.years,
- months=other.months+self.months,
- days=other.days+self.days,
- hours=other.hours+self.hours,
- minutes=other.minutes+self.minutes,
- seconds=other.seconds+self.seconds,
- microseconds=other.microseconds+self.microseconds,
- leapdays=other.leapdays or self.leapdays,
- year=other.year or self.year,
- month=other.month or self.month,
- day=other.day or self.day,
- weekday=other.weekday or self.weekday,
- hour=other.hour or self.hour,
- minute=other.minute or self.minute,
- second=other.second or self.second,
- microsecond=other.microsecond or self.microsecond)
+ months=other.months+self.months,
+ days=other.days+self.days,
+ hours=other.hours+self.hours,
+ minutes=other.minutes+self.minutes,
+ seconds=other.seconds+self.seconds,
+ microseconds=(other.microseconds +
+ self.microseconds),
+ leapdays=other.leapdays or self.leapdays,
+ year=other.year or self.year,
+ month=other.month or self.month,
+ day=other.day or self.day,
+ weekday=other.weekday or self.weekday,
+ hour=other.hour or self.hour,
+ minute=other.minute or self.minute,
+ second=other.second or self.second,
+ microsecond=(other.microsecond or
+ self.microsecond))
if not isinstance(other, datetime.date):
raise TypeError("unsupported type for add operation")
elif self._has_time and not isinstance(other, datetime.datetime):
@@ -289,9 +295,9 @@
weekday, nth = self.weekday.weekday, self.weekday.n or 1
jumpdays = (abs(nth)-1)*7
if nth > 0:
- jumpdays += (7-ret.weekday()+weekday)%7
+ jumpdays += (7-ret.weekday()+weekday) % 7
else:
- jumpdays += (ret.weekday()-weekday)%7
+ jumpdays += (ret.weekday()-weekday) % 7
jumpdays *= -1
ret += datetime.timedelta(days=jumpdays)
return ret
diff --git a/dateutil/rrule.py b/dateutil/rrule.py
index 6e886ec..6dcbb02 100644
--- a/dateutil/rrule.py
+++ b/dateutil/rrule.py
@@ -9,12 +9,9 @@
import datetime
import calendar
import sys
-try:
- import _thread
-except ImportError:
- import thread as _thread
from six import advance_iterator, integer_types
+from six.moves import _thread
__all__ = ["rrule", "rruleset", "rrulestr",
"YEARLY", "MONTHLY", "WEEKLY", "DAILY",
@@ -22,7 +19,7 @@
"MO", "TU", "WE", "TH", "FR", "SA", "SU"]
# Every mask is 7 days longer to handle cross-year weekly periods.
-M366MASK = tuple([1]*31+[2]*29+[3]*31+[4]*30+[5]*31+[6]*30+
+M366MASK = tuple([1]*31+[2]*29+[3]*31+[4]*30+[5]*31+[6]*30 +
[7]*31+[8]*31+[9]*30+[10]*31+[11]*30+[12]*31+[1]*7)
M365MASK = list(M366MASK)
M29, M30, M31 = list(range(1, 30)), list(range(1, 31)), list(range(1, 32))
@@ -50,6 +47,7 @@
easter = None
parser = None
+
class weekday(object):
__slots__ = ["weekday", "n"]
@@ -82,12 +80,13 @@
MO, TU, WE, TH, FR, SA, SU = weekdays = tuple([weekday(x) for x in range(7)])
+
class rrulebase(object):
def __init__(self, cache=False):
if cache:
self._cache = []
self._cache_lock = _thread.allocate_lock()
- self._cache_gen = self._iter()
+ self._cache_gen = self._iter()
self._cache_complete = False
else:
self._cache = None
@@ -162,13 +161,17 @@
# __len__() introduces a large performance penality.
def count(self):
- """ Returns the number of recurrences in this set. It will have go trough the whole recurrence, if this hasn't been done before. """
+ """ Returns the number of recurrences in this set. It will have go
+ trough the whole recurrence, if this hasn't been done before. """
if self._len is None:
- for x in self: pass
+ for x in self:
+ pass
return self._len
def before(self, dt, inc=False):
- """ Returns the last recurrence before the given datetime instance. The inc keyword defines what happens if dt is an occurrence. With inc == True, if dt itself is an occurrence, it will be returned. """
+ """ Returns the last recurrence before the given datetime instance. The
+ inc keyword defines what happens if dt is an occurrence. With
+ inc=True, if dt itself is an occurrence, it will be returned. """
if self._cache_complete:
gen = self._cache
else:
@@ -187,7 +190,9 @@
return last
def after(self, dt, inc=False):
- """ Returns the first recurrence after the given datetime instance. The inc keyword defines what happens if dt is an occurrence. With inc == True, if dt itself is an occurrence, it will be returned. """
+ """ Returns the first recurrence after the given datetime instance. The
+ inc keyword defines what happens if dt is an occurrence. With
+ inc=True, if dt itself is an occurrence, it will be returned. """
if self._cache_complete:
gen = self._cache
else:
@@ -203,7 +208,10 @@
return None
def between(self, after, before, inc=False):
- """ Returns all the occurrences of the rrule between after and before. The inc keyword defines what happens if after and/or before are themselves occurrences. With inc == True, they will be included in the list, if they are found in the recurrence set. """
+ """ Returns all the occurrences of the rrule between after and before.
+ The inc keyword defines what happens if after and/or before are
+ themselves occurrences. With inc=True, they will be included in the
+ list, if they are found in the recurrence set. """
if self._cache_complete:
gen = self._cache
else:
@@ -232,6 +240,7 @@
l.append(i)
return l
+
class rrule(rrulebase):
"""
That's the base of the rrule operation. It accepts all the keywords
@@ -240,49 +249,83 @@
rrule(freq)
- Where freq must be one of YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY, or SECONDLY.
+ Where freq must be one of YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY,
+ or SECONDLY.
Additionally, it supports the following keyword arguments:
:param cache:
- If given, it must be a boolean value specifying to enable or disable caching of results. If you will use the same
- rrule instance multiple times, enabling caching will improve the performance considerably.
+ If given, it must be a boolean value specifying to enable or disable
+ caching of results. If you will use the same rrule instance multiple
+ times, enabling caching will improve the performance considerably.
:param dtstart:
- The recurrence start. Besides being the base for the recurrence, missing parameters in the final recurrence instances will also be extracted from this date. If not
- given, datetime.now() will be used instead.
+ The recurrence start. Besides being the base for the recurrence,
+ missing parameters in the final recurrence instances will also be
+ extracted from this date. If not given, datetime.now() will be used
+ instead.
:param interval:
- The interval between each freq iteration. For example, when using YEARLY, an interval of 2 means once every two years, but with HOURLY, it means once every two hours. The default interval is 1.
+ The interval between each freq iteration. For example, when using
+ YEARLY, an interval of 2 means once every two years, but with HOURLY,
+ it means once every two hours. The default interval is 1.
:param wkst:
- The week start day. Must be one of the MO, TU, WE constants, or an integer, specifying the first day of the week. This will affect recurrences based on weekly periods. The default week start is got from calendar.firstweekday(), and may be modified by calendar.setfirstweekday().
+ The week start day. Must be one of the MO, TU, WE constants, or an
+ integer, specifying the first day of the week. This will affect
+ recurrences based on weekly periods. The default week start is got
+ from calendar.firstweekday(), and may be modified by
+ calendar.setfirstweekday().
:param count:
How many occurrences will be generated.
:param until:
- If given, this must be a datetime instance, that will specify the limit of the recurrence. If a recurrence instance happens to be the same as the datetime instance given in the until keyword, this will be the last occurrence.
+ If given, this must be a datetime instance, that will specify the
+ limit of the recurrence. If a recurrence instance happens to be the
+ same as the datetime instance given in the until keyword, this will
+ be the last occurrence.
:param bysetpos:
- If given, it must be either an integer, or a sequence of integers, positive or negative. Each given integer will specify an occurrence number, corresponding to the nth occurrence of the rule inside the frequency period. For
- example, a bysetpos of -1 if combined with a MONTHLY frequency, and a byweekday of (MO, TU, WE, TH, FR), will result in the last work day of every month.
+ If given, it must be either an integer, or a sequence of integers,
+ positive or negative. Each given integer will specify an occurrence
+ number, corresponding to the nth occurrence of the rule inside the
+ frequency period. For example, a bysetpos of -1 if combined with a
+ MONTHLY frequency, and a byweekday of (MO, TU, WE, TH, FR), will
+ result in the last work day of every month.
:param bymonth:
- If given, it must be either an integer, or a sequence of integers, meaning the months to apply the recurrence to.
+ If given, it must be either an integer, or a sequence of integers,
+ meaning the months to apply the recurrence to.
:param bymonthday:
- If given, it must be either an integer, or a sequence of integers, meaning the month days to apply the recurrence to.
+ If given, it must be either an integer, or a sequence of integers,
+ meaning the month days to apply the recurrence to.
:param byyearday:
- If given, it must be either an integer, or a sequence of integers, meaning the year days to apply the recurrence to.
+ If given, it must be either an integer, or a sequence of integers,
+ meaning the year days to apply the recurrence to.
:param byweekno:
- If given, it must be either an integer, or a sequence of integers, meaning the week numbers to apply the recurrence to. Week numbers have the meaning described in ISO8601, that is, the first week of the year is that containing at least four days of the new year.
+ If given, it must be either an integer, or a sequence of integers,
+ meaning the week numbers to apply the recurrence to. Week numbers
+ have the meaning described in ISO8601, that is, the first week of
+ the year is that containing at least four days of the new year.
:param byweekday:
- If given, it must be either an integer (0 == MO), a sequence of integers, one of the weekday constants (MO, TU, etc), or a sequence of these constants. When given, these variables will define the weekdays where the recurrence will be applied. It's also possible to use an argument n for the weekday instances, which will mean the nth occurrence of this weekday in the period. For example, with MONTHLY, or with YEARLY and BYMONTH, using FR(+1) in byweekday will specify the first friday of the month where the recurrence happens. Notice that in the RFC documentation, this is specified as BYDAY, but was renamed to avoid the ambiguity of that keyword.
+ If given, it must be either an integer (0 == MO), a sequence of
+ integers, one of the weekday constants (MO, TU, etc), or a sequence
+ of these constants. When given, these variables will define the
+ weekdays where the recurrence will be applied. It's also possible to
+ use an argument n for the weekday instances, which will mean the nth
+ occurrence of this weekday in the period. For example, with MONTHLY,
+ or with YEARLY and BYMONTH, using FR(+1) in byweekday will specify the
+ first friday of the month where the recurrence happens. Notice that in
+ the RFC documentation, this is specified as BYDAY, but was renamed to
+ avoid the ambiguity of that keyword.
:param byhour:
- If given, it must be either an integer, or a sequence of integers, meaning the hours to apply the recurrence to.
+ If given, it must be either an integer, or a sequence of integers,
+ meaning the hours to apply the recurrence to.
:param byminute:
- If given, it must be either an integer, or a sequence of integers, meaning the minutes to apply the recurrence to.
+ If given, it must be either an integer, or a sequence of integers,
+ meaning the minutes to apply the recurrence to.
:param bysecond:
- If given, it must be either an integer, or a sequence of integers, meaning the seconds to apply the recurrence to.
+ If given, it must be either an integer, or a sequence of integers,
+ meaning the seconds to apply the recurrence to.
:param byeaster:
- If given, it must be either an integer, or a sequence of integers, positive or negative. Each integer will define an offset from the Easter Sunday. Passing the offset
-
- 0 to byeaster will yield the Easter Sunday itself. This is an extension to the RFC specification.
-
-
+ If given, it must be either an integer, or a sequence of integers,
+ positive or negative. Each integer will define an offset from the
+ Easter Sunday. Passing the offset 0 to byeaster will yield the Easter
+ Sunday itself. This is an extension to the RFC specification.
"""
def __init__(self, freq, dtstart=None,
interval=1, wkst=None, count=None, until=None, bysetpos=None,
@@ -449,8 +492,8 @@
for minute in self._byminute:
for second in self._bysecond:
self._timeset.append(
- datetime.time(hour, minute, second,
- tzinfo=self._tzinfo))
+ datetime.time(hour, minute, second,
+ tzinfo=self._tzinfo))
self._timeset.sort()
self._timeset = tuple(self._timeset)
@@ -478,20 +521,20 @@
ii = _iterinfo(self)
ii.rebuild(year, month)
- getdayset = {YEARLY:ii.ydayset,
- MONTHLY:ii.mdayset,
- WEEKLY:ii.wdayset,
- DAILY:ii.ddayset,
- HOURLY:ii.ddayset,
- MINUTELY:ii.ddayset,
- SECONDLY:ii.ddayset}[freq]
+ getdayset = {YEARLY: ii.ydayset,
+ MONTHLY: ii.mdayset,
+ WEEKLY: ii.wdayset,
+ DAILY: ii.ddayset,
+ HOURLY: ii.ddayset,
+ MINUTELY: ii.ddayset,
+ SECONDLY: ii.ddayset}[freq]
if freq < HOURLY:
timeset = self._timeset
else:
- gettimeset = {HOURLY:ii.htimeset,
- MINUTELY:ii.mtimeset,
- SECONDLY:ii.stimeset}[freq]
+ gettimeset = {HOURLY: ii.htimeset,
+ MINUTELY: ii.mtimeset,
+ SECONDLY: ii.stimeset}[freq]
if ((freq >= HOURLY and
self._byhour and hour not in self._byhour) or
(freq >= MINUTELY and
@@ -520,11 +563,10 @@
ii.mdaymask[i] not in bymonthday and
ii.nmdaymask[i] not in bynmonthday) or
(byyearday and
- ((i < ii.yearlen and i+1 not in byyearday
- and -ii.yearlen+i not in byyearday) or
- (i >= ii.yearlen and i+1-ii.yearlen not in byyearday
- and -ii.nextyearlen+i-ii.yearlen
- not in byyearday)))):
+ ((i < ii.yearlen and i+1 not in byyearday and
+ -ii.yearlen+i not in byyearday) or
+ (i >= ii.yearlen and i+1-ii.yearlen not in byyearday and
+ -ii.nextyearlen+i-ii.yearlen not in byyearday)))):
dayset[i] = None
filtered = True
@@ -538,7 +580,7 @@
daypos, timepos = divmod(pos-1, len(timeset))
try:
i = [x for x in dayset[start:end]
- if x is not None][daypos]
+ if x is not None][daypos]
time = timeset[timepos]
except IndexError:
pass
@@ -640,14 +682,14 @@
fixday = True
filtered = False
if ((not byhour or hour in byhour) and
- (not byminute or minute in byminute)):
+ (not byminute or minute in byminute)):
break
timeset = gettimeset(hour, minute, second)
elif freq == SECONDLY:
if filtered:
# Jump to one iteration before next day
second += (((86399-(hour*3600+minute*60+second))
- //interval)*interval)
+ // interval)*interval)
while True:
second += self._interval
div, mod = divmod(second, 60)
@@ -664,8 +706,8 @@
day += div
fixday = True
if ((not byhour or hour in byhour) and
- (not byminute or minute in byminute) and
- (not bysecond or second in bysecond)):
+ (not byminute or minute in byminute) and
+ (not bysecond or second in bysecond)):
break
timeset = gettimeset(hour, minute, second)
@@ -684,6 +726,7 @@
daysinmonth = calendar.monthrange(year, month)[1]
ii.rebuild(year, month)
+
class _iterinfo(object):
__slots__ = ["rrule", "lastyear", "lastmonth",
"yearlen", "nextyearlen", "yearordinal", "yearweekday",
@@ -723,13 +766,13 @@
self.wnomask = None
else:
self.wnomask = [0]*(self.yearlen+7)
- #no1wkst = firstwkst = self.wdaymask.index(rr._wkst)
- no1wkst = firstwkst = (7-self.yearweekday+rr._wkst)%7
+ # no1wkst = firstwkst = self.wdaymask.index(rr._wkst)
+ no1wkst = firstwkst = (7-self.yearweekday+rr._wkst) % 7
if no1wkst >= 4:
no1wkst = 0
# Number of days in the year, plus the days we got
# from last year.
- wyearlen = self.yearlen+(self.yearweekday-rr._wkst)%7
+ wyearlen = self.yearlen+(self.yearweekday-rr._wkst) % 7
else:
# Number of days in the year, minus the days we
# left in last year.
@@ -775,22 +818,22 @@
# this year.
if -1 not in rr._byweekno:
lyearweekday = datetime.date(year-1, 1, 1).weekday()
- lno1wkst = (7-lyearweekday+rr._wkst)%7
+ lno1wkst = (7-lyearweekday+rr._wkst) % 7
lyearlen = 365+calendar.isleap(year-1)
if lno1wkst >= 4:
lno1wkst = 0
- lnumweeks = 52+(lyearlen+
- (lyearweekday-rr._wkst)%7)%7//4
+ lnumweeks = 52+(lyearlen +
+ (lyearweekday-rr._wkst) % 7) % 7//4
else:
- lnumweeks = 52+(self.yearlen-no1wkst)%7//4
+ lnumweeks = 52+(self.yearlen-no1wkst) % 7//4
else:
lnumweeks = -1
if lnumweeks in rr._byweekno:
for i in range(no1wkst):
self.wnomask[i] = 1
- if (rr._bynweekday and
- (month != self.lastmonth or year != self.lastyear)):
+ if (rr._bynweekday and (month != self.lastmonth or
+ year != self.lastyear)):
ranges = []
if rr._freq == YEARLY:
if rr._bymonth:
@@ -809,10 +852,10 @@
for wday, n in rr._bynweekday:
if n < 0:
i = last+(n+1)*7
- i -= (self.wdaymask[i]-wday)%7
+ i -= (self.wdaymask[i]-wday) % 7
else:
i = first+(n-1)*7
- i += (7-self.wdaymask[i]+wday)%7
+ i += (7-self.wdaymask[i]+wday) % 7
if first <= i <= last:
self.nwdaymask[i] = 1
@@ -843,7 +886,7 @@
for j in range(7):
set[i] = i
i += 1
- #if (not (0 <= i < self.yearlen) or
+ # if (not (0 <= i < self.yearlen) or
# self.wdaymask[i] == self.rrule._wkst):
# This will cross the year boundary, if necessary.
if self.wdaymask[i] == self.rrule._wkst:
@@ -925,21 +968,26 @@
self._exdate = []
def rrule(self, rrule):
- """ Include the given :py:class:`rrule` instance in the recurrence set generation. """
+ """ Include the given :py:class:`rrule` instance in the recurrence set
+ generation. """
self._rrule.append(rrule)
def rdate(self, rdate):
- """ Include the given :py:class:`datetime` instance in the recurrence set generation. """
+ """ Include the given :py:class:`datetime` instance in the recurrence
+ set generation. """
self._rdate.append(rdate)
def exrule(self, exrule):
- """ Include the given rrule instance in the recurrence set
- exclusion list. Dates which are part of the given recurrence
- rules will not be generated, even if some inclusive rrule or rdate matches them."""
+ """ Include the given rrule instance in the recurrence set exclusion
+ list. Dates which are part of the given recurrence rules will not
+ be generated, even if some inclusive rrule or rdate matches them.
+ """
self._exrule.append(exrule)
def exdate(self, exdate):
- """ Include the given datetime instance in the recurrence set exclusion list. Dates included that way will not be generated, even if some inclusive rrule or rdate matches them. """
+ """ Include the given datetime instance in the recurrence set
+ exclusion list. Dates included that way will not be generated,
+ even if some inclusive rrule or rdate matches them. """
self._exdate.append(exdate)
def _iter(self):
@@ -971,6 +1019,7 @@
rlist.sort()
self._len = total
+
class _rrulestr(object):
_freq_map = {"YEARLY": YEARLY,
@@ -981,7 +1030,8 @@
"MINUTELY": MINUTELY,
"SECONDLY": SECONDLY}
- _weekday_map = {"MO":0,"TU":1,"WE":2,"TH":3,"FR":4,"SA":5,"SU":6}
+ _weekday_map = {"MO": 0, "TU": 1, "WE": 2, "TH": 3,
+ "FR": 4, "SA": 5, "SU": 6}
def _handle_int(self, rrkwargs, name, value, **kwargs):
rrkwargs[name.lower()] = int(value)
@@ -989,17 +1039,17 @@
def _handle_int_list(self, rrkwargs, name, value, **kwargs):
rrkwargs[name.lower()] = [int(x) for x in value.split(',')]
- _handle_INTERVAL = _handle_int
- _handle_COUNT = _handle_int
- _handle_BYSETPOS = _handle_int_list
- _handle_BYMONTH = _handle_int_list
+ _handle_INTERVAL = _handle_int
+ _handle_COUNT = _handle_int
+ _handle_BYSETPOS = _handle_int_list
+ _handle_BYMONTH = _handle_int_list
_handle_BYMONTHDAY = _handle_int_list
- _handle_BYYEARDAY = _handle_int_list
- _handle_BYEASTER = _handle_int_list
- _handle_BYWEEKNO = _handle_int_list
- _handle_BYHOUR = _handle_int_list
- _handle_BYMINUTE = _handle_int_list
- _handle_BYSECOND = _handle_int_list
+ _handle_BYYEARDAY = _handle_int_list
+ _handle_BYEASTER = _handle_int_list
+ _handle_BYWEEKNO = _handle_int_list
+ _handle_BYHOUR = _handle_int_list
+ _handle_BYMINUTE = _handle_int_list
+ _handle_BYSECOND = _handle_int_list
def _handle_FREQ(self, rrkwargs, name, value, **kwargs):
rrkwargs["freq"] = self._freq_map[value]
@@ -1010,8 +1060,8 @@
from dateutil import parser
try:
rrkwargs["until"] = parser.parse(value,
- ignoretz=kwargs.get("ignoretz"),
- tzinfos=kwargs.get("tzinfos"))
+ ignoretz=kwargs.get("ignoretz"),
+ tzinfos=kwargs.get("tzinfos"))
except ValueError:
raise ValueError("invalid until date")
@@ -1026,7 +1076,8 @@
break
n = wday[:i] or None
w = wday[i:]
- if n: n = int(n)
+ if n:
+ n = int(n)
l.append(weekdays[self._weekday_map[w]](n))
rrkwargs["byweekday"] = l
@@ -1087,8 +1138,8 @@
i += 1
else:
lines = s.split()
- if (not forceset and len(lines) == 1 and
- (s.find(':') == -1 or s.startswith('RRULE:'))):
+ if (not forceset and len(lines) == 1 and (s.find(':') == -1 or
+ s.startswith('RRULE:'))):
return self._parse_rfc_rrule(lines[0], cache=cache,
dtstart=dtstart, ignoretz=ignoretz,
tzinfos=tzinfos)
@@ -1137,8 +1188,8 @@
tzinfos=tzinfos)
else:
raise ValueError("unsupported property: "+name)
- if (forceset or len(rrulevals) > 1 or
- rdatevals or exrulevals or exdatevals):
+ if (forceset or len(rrulevals) > 1 or rdatevals
+ or exrulevals or exdatevals):
if not parser and (rdatevals or exdatevals):
from dateutil import parser
set = rruleset(cache=cache)
diff --git a/dateutil/test/test.py b/dateutil/test/test.py
index 1f14c27..c00c3a8 100755
--- a/dateutil/test/test.py
+++ b/dateutil/test/test.py
@@ -4,7 +4,6 @@
import unittest
import calendar
import base64
-import os
from datetime import *
@@ -18,7 +17,6 @@
from dateutil import zoneinfo
-
class RelativeDeltaTest(unittest.TestCase):
now = datetime(2003, 9, 17, 20, 54, 47, 282310)
today = date(2003, 9, 17)
@@ -30,6 +28,7 @@
def testNextMonthPlusOneWeek(self):
self.assertEqual(self.now+relativedelta(months=+1, weeks=+1),
datetime(2003, 10, 24, 20, 54, 47, 282310))
+
def testNextMonthPlusOneWeek10am(self):
self.assertEqual(self.today +
relativedelta(months=+1, weeks=+1, hour=10),
@@ -86,7 +85,6 @@
self.assertEqual(self.today+relativedelta(weekday=WE),
date(2003, 9, 17))
-
def testNextWenesdayNotToday(self):
self.assertEqual(self.today+relativedelta(days=+1, weekday=WE),
date(2003, 9, 24))
@@ -180,8 +178,8 @@
self.assertEqual(datetime(2000, 1, 1) + relativedelta(days=28) / 28,
datetime(2000, 1, 2))
-class RRuleTest(unittest.TestCase):
+class RRuleTest(unittest.TestCase):
def testYearly(self):
self.assertEqual(list(rrule(YEARLY,
count=3,
@@ -552,7 +550,6 @@
datetime(1998, 3, 2, 9, 0),
datetime(1999, 1, 2, 9, 0)])
-
def testMonthlyByMonthDay(self):
self.assertEqual(list(rrule(MONTHLY,
count=3,
@@ -692,7 +689,6 @@
datetime(1999, 4, 10, 9, 0),
datetime(1999, 7, 19, 9, 0)])
-
def testMonthlyByWeekNo(self):
self.assertEqual(list(rrule(MONTHLY,
count=3,
@@ -2534,7 +2530,7 @@
def testGetItemSlice(self):
self.assertEqual(rrule(DAILY,
- #count=3,
+ # count=3,
dtstart=parse("19970902T090000"))[1:2],
[datetime(1997, 9, 3, 9, 0)])
@@ -2568,10 +2564,8 @@
self.assertEqual(datetime(1997, 9, 3, 9, 0) not in rr, False)
def testBefore(self):
- self.assertEqual(rrule(DAILY,
- #count=5,
- dtstart=parse("19970902T090000"))
- .before(parse("19970905T090000")),
+ self.assertEqual(rrule(DAILY, # count=5
+ dtstart=parse("19970902T090000")).before(parse("19970905T090000")),
datetime(1997, 9, 4, 9, 0))
def testBeforeInc(self):
diff --git a/dateutil/tz.py b/dateutil/tz.py
index 8b07844..6ccace8 100644
--- a/dateutil/tz.py
+++ b/dateutil/tz.py
@@ -8,7 +8,6 @@
timezone.
"""
import datetime
-import platform
import struct
import time
import sys
@@ -45,6 +44,7 @@
ZERO = datetime.timedelta(0)
EPOCHORDINAL = datetime.datetime.utcfromtimestamp(0).toordinal()
+
class tzutc(datetime.tzinfo):
def utcoffset(self, dt):
@@ -69,6 +69,7 @@
__reduce__ = object.__reduce__
+
class tzoffset(datetime.tzinfo):
def __init__(self, name, offset):
@@ -99,6 +100,7 @@
__reduce__ = object.__reduce__
+
class tzlocal(datetime.tzinfo):
_std_offset = datetime.timedelta(seconds=-time.timezone)
@@ -133,18 +135,18 @@
#
# The code above yields the following result:
#
- #>>> import tz, datetime
- #>>> t = tz.tzlocal()
- #>>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname()
- #'BRDT'
- #>>> datetime.datetime(2003,2,16,0,tzinfo=t).tzname()
- #'BRST'
- #>>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname()
- #'BRST'
- #>>> datetime.datetime(2003,2,15,22,tzinfo=t).tzname()
- #'BRDT'
- #>>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname()
- #'BRDT'
+ # >>> import tz, datetime
+ # >>> t = tz.tzlocal()
+ # >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname()
+ # 'BRDT'
+ # >>> datetime.datetime(2003,2,16,0,tzinfo=t).tzname()
+ # 'BRST'
+ # >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname()
+ # 'BRST'
+ # >>> datetime.datetime(2003,2,15,22,tzinfo=t).tzname()
+ # 'BRDT'
+ # >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname()
+ # 'BRDT'
#
# Here is a more stable implementation:
#
@@ -169,6 +171,7 @@
__reduce__ = object.__reduce__
+
class _ttinfo(object):
__slots__ = ["offset", "delta", "isdst", "abbr", "isstd", "isgmt"]
@@ -208,6 +211,7 @@
if name in state:
setattr(self, name, state[name])
+
class tzfile(datetime.tzinfo):
# http://www.twinsun.com/tz/tz-link.htm
@@ -320,9 +324,9 @@
# by time.
# Not used, for now
- if leapcnt:
- leap = struct.unpack(">%dl" % (leapcnt*2),
- fileobj.read(leapcnt*8))
+ # if leapcnt:
+ # leap = struct.unpack(">%dl" % (leapcnt*2),
+ # fileobj.read(leapcnt*8))
# Then there are tzh_ttisstdcnt standard/wall
# indicators, each stored as a one-byte value;
@@ -356,7 +360,7 @@
# Build ttinfo list
self._ttinfo_list = []
for i in range(typecnt):
- gmtoff, isdst, abbrind = ttinfo[i]
+ gmtoff, isdst, abbrind = ttinfo[i]
# Round to full-minutes if that's not the case. Python's
# datetime doesn't accept sub-minute timezones. Check
# http://python.org/sf/1447945 for some information.
@@ -491,7 +495,6 @@
def __ne__(self, other):
return not self.__eq__(other)
-
def __repr__(self):
return "%s(%s)" % (self.__class__.__name__, repr(self._filename))
@@ -500,8 +503,8 @@
raise ValueError("Unpickable %s class" % self.__class__.__name__)
return (self.__class__, (self._filename,))
-class tzrange(datetime.tzinfo):
+class tzrange(datetime.tzinfo):
def __init__(self, stdabbr, stdoffset=None,
dstabbr=None, dstoffset=None,
start=None, end=None):
@@ -522,12 +525,12 @@
self._dst_offset = ZERO
if dstabbr and start is None:
self._start_delta = relativedelta.relativedelta(
- hours=+2, month=4, day=1, weekday=relativedelta.SU(+1))
+ hours=+2, month=4, day=1, weekday=relativedelta.SU(+1))
else:
self._start_delta = start
if dstabbr and end is None:
self._end_delta = relativedelta.relativedelta(
- hours=+1, month=10, day=31, weekday=relativedelta.SU(-1))
+ hours=+1, month=10, day=31, weekday=relativedelta.SU(-1))
else:
self._end_delta = end
@@ -580,6 +583,7 @@
__reduce__ = object.__reduce__
+
class tzstr(tzrange):
def __init__(self, s):
@@ -655,9 +659,10 @@
def __repr__(self):
return "%s(%s)" % (self.__class__.__name__, repr(self._s))
+
class _tzicalvtzcomp(object):
def __init__(self, tzoffsetfrom, tzoffsetto, isdst,
- tzname=None, rrule=None):
+ tzname=None, rrule=None):
self.tzoffsetfrom = datetime.timedelta(seconds=tzoffsetfrom)
self.tzoffsetto = datetime.timedelta(seconds=tzoffsetto)
self.tzoffsetdiff = self.tzoffsetto-self.tzoffsetfrom
@@ -665,6 +670,7 @@
self.tzname = tzname
self.rrule = rrule
+
class _tzicalvtz(datetime.tzinfo):
def __init__(self, tzid, comps=[]):
self._tzid = tzid
@@ -728,6 +734,7 @@
__reduce__ = object.__reduce__
+
class tzical(object):
def __init__(self, fileobj):
global rrule
@@ -736,7 +743,8 @@
if isinstance(fileobj, string_types):
self._s = fileobj
- fileobj = open(fileobj, 'r') # ical should be encoded in UTF-8 with CRLF
+ # ical should be encoded in UTF-8 with CRLF
+ fileobj = open(fileobj, 'r')
elif hasattr(fileobj, "name"):
self._s = fileobj.name
else:
@@ -764,7 +772,7 @@
if not s:
raise ValueError("empty offset")
if s[0] in ('+', '-'):
- signal = (-1, +1)[s[0]=='+']
+ signal = (-1, +1)[s[0] == '+']
s = s[1:]
else:
signal = +1
@@ -825,7 +833,8 @@
if not tzid:
raise ValueError("mandatory TZID not found")
if not comps:
- raise ValueError("at least one component is needed")
+ raise ValueError(
+ "at least one component is needed")
# Process vtimezone
self._vtz[tzid] = _tzicalvtz(tzid, comps)
invtz = False
@@ -833,9 +842,11 @@
if not founddtstart:
raise ValueError("mandatory DTSTART not found")
if tzoffsetfrom is None:
- raise ValueError("mandatory TZOFFSETFROM not found")
+ raise ValueError(
+ "mandatory TZOFFSETFROM not found")
if tzoffsetto is None:
- raise ValueError("mandatory TZOFFSETFROM not found")
+ raise ValueError(
+ "mandatory TZOFFSETFROM not found")
# Process component
rr = None
if rrulelines:
@@ -858,15 +869,18 @@
rrulelines.append(line)
elif name == "TZOFFSETFROM":
if parms:
- raise ValueError("unsupported %s parm: %s "%(name, parms[0]))
+ raise ValueError(
+ "unsupported %s parm: %s " % (name, parms[0]))
tzoffsetfrom = self._parse_offset(value)
elif name == "TZOFFSETTO":
if parms:
- raise ValueError("unsupported TZOFFSETTO parm: "+parms[0])
+ raise ValueError(
+ "unsupported TZOFFSETTO parm: "+parms[0])
tzoffsetto = self._parse_offset(value)
elif name == "TZNAME":
if parms:
- raise ValueError("unsupported TZNAME parm: "+parms[0])
+ raise ValueError(
+ "unsupported TZNAME parm: "+parms[0])
tzname = value
elif name == "COMMENT":
pass
@@ -875,7 +889,8 @@
else:
if name == "TZID":
if parms:
- raise ValueError("unsupported TZID parm: "+parms[0])
+ raise ValueError(
+ "unsupported TZID parm: "+parms[0])
tzid = value
elif name in ("TZURL", "LAST-MODIFIED", "COMMENT"):
pass
@@ -896,6 +911,7 @@
TZFILES = []
TZPATHS = []
+
def gettz(name=None):
tz = None
if not name:
diff --git a/dateutil/zoneinfo/__init__.py b/dateutil/zoneinfo/__init__.py
index 442d4ea..53d9dfe 100644
--- a/dateutil/zoneinfo/__init__.py
+++ b/dateutil/zoneinfo/__init__.py
@@ -43,15 +43,19 @@
with _tar_open(fileobj=zonefile_stream, mode='r') as tf:
# dict comprehension does not work on python2.6
# TODO: get back to the nicer syntax when we ditch python2.6
- # self.zones = {zf.name: tzfile(tf.extractfile(zf), filename = zf.name)
+ # self.zones = {zf.name: tzfile(tf.extractfile(zf),
+ # filename = zf.name)
# for zf in tf.getmembers() if zf.isfile()}
- self.zones = dict((zf.name, tzfile(tf.extractfile(zf), filename=zf.name))
+ self.zones = dict((zf.name, tzfile(tf.extractfile(zf),
+ filename=zf.name))
for zf in tf.getmembers() if zf.isfile())
- # deal with links: They'll point to their parent object. Less waste of memory
+ # deal with links: They'll point to their parent object. Less
+ # waste of memory
# links = {zl.name: self.zones[zl.linkname]
- # for zl in tf.getmembers() if zl.islnk() or zl.issym()}
+ # for zl in tf.getmembers() if zl.islnk() or zl.issym()}
links = dict((zl.name, self.zones[zl.linkname])
- for zl in tf.getmembers() if zl.islnk() or zl.issym())
+ for zl in tf.getmembers() if
+ zl.islnk() or zl.issym())
self.zones.update(links)
else:
self.zones = dict()
@@ -83,8 +87,6 @@
moduledir = os.path.dirname(__file__)
try:
with _tar_open(filename) as tf:
- # The "backwards" zone file contains links to other files, so must be
- # processed as last
for name in zonegroups:
tf.extract(name, tmpdir)
filepaths = [os.path.join(tmpdir, n) for n in zonegroups]
diff --git a/updatezinfo.py b/updatezinfo.py
index ade4d05..ed688de 100755
--- a/updatezinfo.py
+++ b/updatezinfo.py
@@ -10,18 +10,21 @@
METADATA_FILE = "zonefile_metadata.json"
+
def main():
- with io.open(METADATA_FILE,'r') as f:
+ with io.open(METADATA_FILE, 'r') as f:
metadata = json.load(f)
if not os.path.isfile(metadata['tzdata_file']):
print("Downloading tz file from iana")
- request.urlretrieve(os.path.join(metadata['releases_url'],metadata['tzdata_file']), metadata['tzdata_file'])
- with open(metadata['tzdata_file'],'rb') as tzfile:
+ request.urlretrieve(os.path.join(metadata['releases_url'],
+ metadata['tzdata_file']),
+ metadata['tzdata_file'])
+ with open(metadata['tzdata_file'], 'rb') as tzfile:
sha_hasher = hashlib.sha512()
sha_hasher.update(tzfile.read())
sha_512_file = sha_hasher.hexdigest()
- assert metadata['tzdata_file_sha512'] == sha_512_file, "SHA failed for downloaded tz file"
+ assert metadata['tzdata_file_sha512'] == sha_512_file, "SHA failed for"
print("Updating timezone information...")
rebuild(metadata['tzdata_file'], zonegroups=metadata['zonegroups'])
print("Done.")