X-Git-Url: https://git.tokkee.org/?a=blobdiff_plain;f=roundup%2Fdate.py;h=8f60a725e7eddfb56e73bea99a234b59931f6eda;hb=d53f951d3021166e7f3bebc037708accdecb7ff5;hp=c214cd1350e050c457bfe3546533dadd1c0c4cec;hpb=dcfcaa9b682cba3f5abc10c177869f2b8b40386f;p=roundup.git diff --git a/roundup/date.py b/roundup/date.py index c214cd1..8f60a72 100644 --- a/roundup/date.py +++ b/roundup/date.py @@ -15,15 +15,24 @@ # BASIS, AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE, # SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. # -# $Id: date.py,v 1.47 2003-03-10 00:22:20 richard Exp $ +# $Id: date.py,v 1.60 2004-02-11 23:55:08 richard Exp $ -__doc__ = """ -Date, time and time interval handling. +"""Date, time and time interval handling. """ +__docformat__ = 'restructuredtext' import time, re, calendar, types from i18n import _ +def _add_granularity(src, order, value = 1): + '''Increment first non-None value in src dictionary ordered by 'order' + parameter + ''' + for gran in order: + if src[gran]: + src[gran] = int(src[gran]) + value + break + class Date: ''' As strings, date-and-time stamps are specified with the date in @@ -42,6 +51,7 @@ class Date: care of these conversions. In the following examples, suppose that yyyy is the current year, mm is the current month, and dd is the current day of the month; and suppose that the user is on Eastern Standard Time. + Examples:: "2000-04-17" means "01-25" means @@ -50,6 +60,8 @@ class Date: "11-07.09:32:43" means "14:25" means "8:47:11" means + "2003" means + "2003-06" means "." means "right now" The Date class should understand simple date expressions of the form @@ -58,9 +70,8 @@ class Date: separately. For example, when evaluating "2000-06-25 + 1m 10d", we first add one month to get 2000-07-25, then add 10 days to get 2000-08-04 (rather than trying to decide whether 1m 10d means 38 or 40 - or 41 days). + or 41 days). Example usage:: - Example usage: >>> Date(".") >>> _.local(-5) @@ -80,21 +91,92 @@ class Date: minute, second) is the serialisation format returned by the serialise() method, and is accepted as an argument on instatiation. ''' - def __init__(self, spec='.', offset=0): + + def __init__(self, spec='.', offset=0, add_granularity=0): """Construct a date given a specification and a time zone offset. - 'spec' is a full date or a partial form, with an optional - added or subtracted interval. Or a date 9-tuple. - 'offset' is the local time zone offset from GMT in hours. + 'spec' + is a full date or a partial form, with an optional added or + subtracted interval. Or a date 9-tuple. + 'offset' + is the local time zone offset from GMT in hours. """ if type(spec) == type(''): - self.set(spec, offset=offset) + self.set(spec, offset=offset, add_granularity=add_granularity) else: y,m,d,H,M,S,x,x,x = spec ts = calendar.timegm((y,m,d,H+offset,M,S,0,0,0)) self.year, self.month, self.day, self.hour, self.minute, \ self.second, x, x, x = time.gmtime(ts) + usagespec='[yyyy]-[mm]-[dd].[H]H:MM[:SS][offset]' + def set(self, spec, offset=0, date_re=re.compile(r''' + ((?P\d\d\d\d)([/-](?P\d\d?)([/-](?P\d\d?))?)? # yyyy[-mm[-dd]] + |(?P\d\d?)[/-](?P\d\d?))? # or mm-dd + (?P\.)? # . + (((?P\d?\d):(?P\d\d))?(:(?P\d\d))?)? # hh:mm:ss + (?P.+)? # offset + ''', re.VERBOSE), serialised_re=re.compile(r''' + (\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d) + ''', re.VERBOSE), add_granularity=0): + ''' set the date to the value in spec + ''' + + m = serialised_re.match(spec) + if m is not None: + # we're serialised - easy! + self.year, self.month, self.day, self.hour, self.minute, \ + self.second = map(int, m.groups()[:6]) + return + + # not serialised data, try usual format + m = date_re.match(spec) + if m is None: + raise ValueError, _('Not a date spec: %s' % self.usagespec) + + info = m.groupdict() + + if add_granularity: + _add_granularity(info, 'SMHdmyab') + + # get the current date as our default + y,m,d,H,M,S,x,x,x = time.gmtime(time.time()) + + if info['y'] is not None or info['a'] is not None: + if info['y'] is not None: + y = int(info['y']) + m,d = (1,1) + if info['m'] is not None: + m = int(info['m']) + if info['d'] is not None: + d = int(info['d']) + if info['a'] is not None: + m = int(info['a']) + d = int(info['b']) + H = -offset + M = S = 0 + + # override hour, minute, second parts + if info['H'] is not None and info['M'] is not None: + H = int(info['H']) - offset + M = int(info['M']) + S = 0 + if info['S'] is not None: S = int(info['S']) + + if add_granularity: + S = S - 1 + + # now handle the adjustment of hour + ts = calendar.timegm((y,m,d,H,M,S,0,0,0)) + self.year, self.month, self.day, self.hour, self.minute, \ + self.second, x, x, x = time.gmtime(ts) + + if info.get('o', None): + try: + self.applyInterval(Interval(info['o'], allowdate=0)) + except ValueError: + raise ValueError, _('Not a date spec: %s' % self.usagespec) + def addInterval(self, interval): ''' Add the interval to this date, returning the date tuple ''' @@ -110,13 +192,13 @@ class Date: # now cope with under- and over-flow # first do the time while (second < 0 or second > 59 or minute < 0 or minute > 59 or - hour < 0 or hour > 59): + hour < 0 or hour > 23): if second < 0: minute -= 1; second += 60 elif second > 59: minute += 1; second -= 60 if minute < 0: hour -= 1; minute += 60 elif minute > 59: hour += 1; minute -= 60 if hour < 0: day -= 1; hour += 24 - elif hour > 59: day += 1; hour -= 24 + elif hour > 23: day += 1; hour -= 24 # fix up the month so we're within range while month < 1 or month > 12: @@ -124,24 +206,31 @@ class Date: if month > 12: year += 1; month -= 12 # now do the days, now that we know what month we're in - mdays = calendar.mdays - if month == 2 and calendar.isleap(year): month_days = 29 - else: month_days = mdays[month] - while month < 1 or month > 12 or day < 0 or day > month_days: + def get_mdays(year, month): + if month == 2 and calendar.isleap(year): return 29 + else: return calendar.mdays[month] + + while month < 1 or month > 12 or day < 1 or day > get_mdays(year,month): # now to day under/over - if day < 0: month -= 1; day += month_days - elif day > month_days: month += 1; day -= month_days + if day < 1: + # When going backwards, decrement month, then increment days + month -= 1 + day += get_mdays(year,month) + elif day > get_mdays(year,month): + # When going forwards, decrement days, then increment month + day -= get_mdays(year,month) + month += 1 # possibly fix up the month so we're within range while month < 1 or month > 12: - if month < 1: year -= 1; month += 12 + if month < 1: year -= 1; month += 12 ; day += 31 if month > 12: year += 1; month -= 12 - # re-figure the number of days for this month - if month == 2 and calendar.isleap(year): month_days = 29 - else: month_days = mdays[month] return (year, month, day, hour, minute, second, 0, 0, 0) + def differenceDate(self, other): + "Return the difference between this date and another date" + def applyInterval(self, interval): ''' Apply the interval to this date ''' @@ -166,29 +255,29 @@ class Date: assert isinstance(other, Date), 'May only subtract Dates or Intervals' - # TODO this code will fall over laughing if the dates cross - # leap years, phases of the moon, .... + return self.dateDelta(other) + + def dateDelta(self, other): + """ Produce an Interval of the difference between this date + and another date. Only returns days:hours:minutes:seconds. + """ + # Returning intervals larger than a day is almost + # impossible - months, years, weeks, are all so imprecise. a = calendar.timegm((self.year, self.month, self.day, self.hour, self.minute, self.second, 0, 0, 0)) b = calendar.timegm((other.year, other.month, other.day, other.hour, other.minute, other.second, 0, 0, 0)) diff = a - b - if diff < 0: + if diff > 0: sign = 1 - diff = -diff else: sign = -1 + diff = -diff S = diff%60 M = (diff/60)%60 - H = (diff/(60*60))%60 - if H>1: S = 0 - d = (diff/(24*60*60))%30 - if d>1: H = S = M = 0 - m = (diff/(30*24*60*60))%12 - if m>1: H = S = M = 0 - y = (diff/(365*24*60*60)) - if y>1: d = H = S = M = 0 - return Interval((y, m, d, H, M, S), sign=sign) + H = (diff/(60*60))%24 + d = diff/(24*60*60) + return Interval((0, 0, d, H, M, S), sign=sign) def __cmp__(self, other): """Compare this date to another date.""" @@ -219,59 +308,6 @@ class Date: return ' ' + str[1:] return str - def set(self, spec, offset=0, date_re=re.compile(r''' - (((?P\d\d\d\d)-)?((?P\d\d?)-(?P\d\d?))?)? # yyyy-mm-dd - (?P\.)? # . - (((?P\d?\d):(?P\d\d))?(:(?P\d\d))?)? # hh:mm:ss - (?P.+)? # offset - ''', re.VERBOSE), serialised_re=re.compile(r''' - (\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d) - ''', re.VERBOSE)): - ''' set the date to the value in spec - ''' - m = serialised_re.match(spec) - if m is not None: - # we're serialised - easy! - self.year, self.month, self.day, self.hour, self.minute, \ - self.second = map(int, m.groups()[:6]) - return - - # not serialised data, try usual format - m = date_re.match(spec) - if m is None: - raise ValueError, _('Not a date spec: [[yyyy-]mm-dd].' - '[[h]h:mm[:ss]][offset]') - - info = m.groupdict() - - # get the current date as our default - y,m,d,H,M,S,x,x,x = time.gmtime(time.time()) - - # override year, month, day parts - if info['m'] is not None and info['d'] is not None: - m = int(info['m']) - d = int(info['d']) - if info['y'] is not None: - y = int(info['y']) - # time defaults to 00:00:00 GMT - offset (local midnight) - H = -offset - M = S = 0 - - # override hour, minute, second parts - if info['H'] is not None and info['M'] is not None: - H = int(info['H']) - offset - M = int(info['M']) - S = 0 - if info['S'] is not None: S = int(info['S']) - - # now handle the adjustment of hour - ts = calendar.timegm((y,m,d,H,M,S,0,0,0)) - self.year, self.month, self.day, self.hour, self.minute, \ - self.second, x, x, x = time.gmtime(ts) - - if info.get('o', None): - self.applyInterval(Interval(info['o'])) - def __repr__(self): return ''%self.__str__() @@ -289,6 +325,11 @@ class Date: return '%4d%02d%02d%02d%02d%02d'%(self.year, self.month, self.day, self.hour, self.minute, self.second) + def timestamp(self): + ''' return a UNIX timestamp for this date ''' + return calendar.timegm((self.year, self.month, self.day, self.hour, + self.minute, self.second, 0, 0, 0)) + class Interval: ''' Date intervals are specified using the suffixes "y", "m", and "d". The @@ -317,6 +358,10 @@ class Interval: >>> Interval('1:00')/2 + >>> Interval('2003-03-18') + + >>> Interval('-4d 2003-03-18') + Interval arithmetic is handled in a couple of special ways, trying to cater for the most common cases. Fundamentally, Intervals which @@ -337,10 +382,10 @@ class Interval: TODO: more examples, showing the order of addition operation ''' - def __init__(self, spec, sign=1): + def __init__(self, spec, sign=1, allowdate=1, add_granularity=0): """Construct an interval given a specification.""" if type(spec) == type(''): - self.set(spec) + self.set(spec, allowdate=allowdate, add_granularity=add_granularity) else: if len(spec) == 7: self.sign, self.year, self.month, self.day, self.hour, \ @@ -351,6 +396,69 @@ class Interval: self.year, self.month, self.day, self.hour, self.minute, \ self.second = spec + def set(self, spec, allowdate=1, interval_re=re.compile(''' + \s*(?P[-+])? # + or - + \s*((?P\d+\s*)y)? # year + \s*((?P\d+\s*)m)? # month + \s*((?P\d+\s*)w)? # week + \s*((?P\d+\s*)d)? # day + \s*(((?P\d+):(?P\d+))?(:(?P\d+))?)? # time + \s*(?P + (\d\d\d\d[/-])?(\d\d?)?[/-](\d\d?)? # [yyyy-]mm-dd + \.? # . + (\d?\d:\d\d)?(:\d\d)? # hh:mm:ss + )?''', re.VERBOSE), serialised_re=re.compile(''' + (?P[+-])?1?(?P([ ]{3}\d|\d{4}))(?P\d{2})(?P\d{2}) + (?P\d{2})(?P\d{2})(?P\d{2})''', re.VERBOSE), + add_granularity=0): + ''' set the date to the value in spec + ''' + self.year = self.month = self.week = self.day = self.hour = \ + self.minute = self.second = 0 + self.sign = 1 + m = serialised_re.match(spec) + if not m: + m = interval_re.match(spec) + if not m: + raise ValueError, _('Not an interval spec: [+-] [#y] [#m] [#w] ' + '[#d] [[[H]H:MM]:SS] [date spec]') + else: + allowdate = 0 + + # pull out all the info specified + info = m.groupdict() + if add_granularity: + _add_granularity(info, 'SMHdwmy', (info['s']=='-' and -1 or 1)) + + valid = 0 + for group, attr in {'y':'year', 'm':'month', 'w':'week', 'd':'day', + 'H':'hour', 'M':'minute', 'S':'second'}.items(): + if info.get(group, None) is not None: + valid = 1 + setattr(self, attr, int(info[group])) + + # make sure it's valid + if not valid and not info['D']: + raise ValueError, _('Not an interval spec: [+-] [#y] [#m] [#w] ' + '[#d] [[[H]H:MM]:SS]') + + if self.week: + self.day = self.day + self.week*7 + + if info['s'] is not None: + self.sign = {'+':1, '-':-1}[info['s']] + + # use a date spec if one is given + if allowdate and info['D'] is not None: + now = Date('.') + date = Date(info['D']) + # if no time part was specified, nuke it in the "now" date + if not date.hour or date.minute or date.second: + now.hour = now.minute = now.second = 0 + if date != now: + y = now - (date + self) + self.__init__(y.get_tuple()) + def __cmp__(self, other): """Compare this interval to another interval.""" if other is None: @@ -413,11 +521,11 @@ class Interval: raise TypeError, "Can't add %r"%other def __div__(self, other): - ''' Divide this interval by an int value. + """ Divide this interval by an int value. Can't divide years and months sensibly in the _same_ calculation as days/time, so raise an error in that situation. - ''' + """ try: other = float(other) except TypeError: @@ -455,40 +563,6 @@ class Interval: d = seconds / 24 return Interval((sign, 0, 0, d, H, M, S)) - def set(self, spec, interval_re=re.compile(''' - \s*(?P[-+])? # + or - - \s*((?P\d+\s*)y)? # year - \s*((?P\d+\s*)m)? # month - \s*((?P\d+\s*)w)? # week - \s*((?P\d+\s*)d)? # day - \s*(((?P\d+):(?P\d+))?(:(?P\d+))?)? # time - \s*''', re.VERBOSE), serialised_re=re.compile(''' - (?P[+-])?1?(?P([ ]{3}\d|\d{4}))(?P\d{2})(?P\d{2}) - (?P\d{2})(?P\d{2})(?P\d{2})''', re.VERBOSE)): - ''' set the date to the value in spec - ''' - self.year = self.month = self.week = self.day = self.hour = \ - self.minute = self.second = 0 - self.sign = 1 - m = serialised_re.match(spec) - if not m: - m = interval_re.match(spec) - if not m: - raise ValueError, _('Not an interval spec: [+-] [#y] [#m] [#w] ' - '[#d] [[[H]H:MM]:SS]') - - info = m.groupdict() - for group, attr in {'y':'year', 'm':'month', 'w':'week', 'd':'day', - 'H':'hour', 'M':'minute', 'S':'second'}.items(): - if info.get(group, None) is not None: - setattr(self, attr, int(info[group])) - - if self.week: - self.day = self.day + self.week*7 - - if info['s'] is not None: - self.sign = {'+':1, '-':-1}[info['s']] - def __repr__(self): return ''%self.__str__() @@ -497,9 +571,9 @@ class Interval: ''' if self.year: if self.year == 1: - return _('1 year') + s = _('1 year') else: - return _('%(number)s years')%{'number': self.year} + s = _('%(number)s years')%{'number': self.year} elif self.month or self.day > 13: days = (self.month * 30) + self.day if days > 28: @@ -543,7 +617,7 @@ class Interval: if self.sign < 0: s = s + _(' ago') else: - s = _('in') + s + s = _('in ') + s return s def get_tuple(self): @@ -556,13 +630,13 @@ class Interval: self.day, self.hour, self.minute, self.second) def fixTimeOverflow(time): - ''' Handle the overflow in the time portion (H, M, S) of "time": + """ Handle the overflow in the time portion (H, M, S) of "time": (sign, y,m,d,H,M,S) Overflow and underflow will at most affect the _days_ portion of the date. We do not overflow days to months as we don't know _how_ to, generally. - ''' + """ # XXX we could conceivably use this function for handling regular dates # XXX too - we just need to interrogate the month/year for the day # XXX overflow... @@ -588,20 +662,24 @@ def fixTimeOverflow(time): return (sign, y, m, d, H, M, S) class Range: - """ - Represents range between two values + """Represents range between two values Ranges can be created using one of theese two alternative syntaxes: - 1. Native english syntax: + 1. Native english syntax:: + [[From] ][ To ] - Keywords "From" and "To" are case insensitive. Keyword "From" is optional. - 2. "Geek" syntax: - [][; ] + Keywords "From" and "To" are case insensitive. Keyword "From" is + optional. + + 2. "Geek" syntax:: + + [][; ] Either first or second can be omitted in both syntaxes. - Examples (consider local time is Sat Mar 8 22:07:48 EET 2003): + Examples (consider local time is Sat Mar 8 22:07:48 EET 2003):: + >>> Range("from 2-12 to 4-2") @@ -621,16 +699,20 @@ class Range: """ - def __init__(self, spec, type, **params): - """Initializes Range of type from given string. + def __init__(self, spec, Type, allow_granularity=1, **params): + """Initializes Range of type from given string. Sets two properties - from_value and to_value. None assigned to any of this properties means "infinitum" (-infinitum to from_value and - +infinitum to to_value) + +infinitum to to_value) + + The Type parameter here should be class itself (e.g. Date), not a + class instance. + """ - self.range_type = type - re_range = r'(?:^|(?:from)?(.+?))(?:to(.+?)$|$)' - re_geek_range = r'(?:^|(.+?))(?:;(.+?)$|$)' + self.range_type = Type + re_range = r'(?:^|from(.+?))(?:to(.+?)$|$)' + re_geek_range = r'(?:^|(.+?));(?:(.+?)$|$)' # Check which syntax to use if spec.find(';') == -1: # Native english @@ -641,11 +723,15 @@ class Range: if mch_range: self.from_value, self.to_value = mch_range.groups() if self.from_value: - self.from_value = type(self.from_value.strip(), **params) + self.from_value = Type(self.from_value.strip(), **params) if self.to_value: - self.to_value = type(self.to_value.strip(), **params) + self.to_value = Type(self.to_value.strip(), **params) else: - raise ValueError, "Invalid range" + if allow_granularity: + self.from_value = Type(spec, **params) + self.to_value = Type(spec, add_granularity=1, **params) + else: + raise ValueError, "Invalid range" def __str__(self): return "from %s to %s" % (self.from_value, self.to_value) @@ -654,12 +740,17 @@ class Range: return "" % self.__str__() def test_range(): - rspecs = ("from 2-12 to 4-2", "18:00 TO +2m", "12:00", "tO +3d", - "2002-11-10; 2002-12-12", "; 20:00 +1d") + rspecs = ("from 2-12 to 4-2", "from 18:00 TO +2m", "12:00;", "tO +3d", + "2002-11-10; 2002-12-12", "; 20:00 +1d", '2002-10-12') + rispecs = ('from -1w 2d 4:32 to 4d', '-2w 1d') for rspec in rspecs: print '>>> Range("%s")' % rspec print `Range(rspec, Date)` print + for rspec in rispecs: + print '>>> Range("%s")' % rspec + print `Range(rspec, Interval)` + print def test(): intervals = (" 3w 1 d 2:00", " + 2d", "3w") @@ -668,7 +759,7 @@ def test(): print `Interval(interval)` dates = (".", "2000-06-25.19:34:02", ". + 2d", "1997-04-17", "01-25", - "08-13.22:13", "14:25") + "08-13.22:13", "14:25", '2002-12') for date in dates: print '>>> Date("%s")'%date print `Date(date)` @@ -679,6 +770,6 @@ def test(): print `Date(date) + Interval(interval)` if __name__ == '__main__': - test_range() + test() # vim: set filetype=python ts=4 sw=4 et si