diff --git a/roundup/date.py b/roundup/date.py
index 3e6559ff0bad626efeee0264823ee649d33b00ef..365aa80b07cc670a641400ea896e0f9a753f8cd0 100644 (file)
--- a/roundup/date.py
+++ b/roundup/date.py
# BASIS, AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,
# SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
#
-# $Id: date.py,v 1.46 2003-03-08 20:41:45 kedder Exp $
+# $Id: date.py,v 1.54 2003-04-23 11:48:05 richard Exp $
__doc__ = """
Date, time and time interval handling.
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
"11-07.09:32:43" means <Date yyyy-11-07.14:32:43>
"14:25" means <Date yyyy-mm-dd.19:25:00>
"8:47:11" means <Date yyyy-mm-dd.13:47:11>
+ "2003" means <Date 2003-01-01.00:00:00>
+ "2003-06" means <Date 2003-06-01.00:00:00>
"." means "right now"
The Date class should understand simple date expressions of the form
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
'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<y>\d\d\d\d)([/-](?P<m>\d\d?)([/-](?P<d>\d\d?))?)? # yyyy[-mm[-dd]]
+ |(?P<a>\d\d?)[/-](?P<b>\d\d?))? # or mm-dd
+ (?P<n>\.)? # .
+ (((?P<H>\d?\d):(?P<M>\d\d))?(:(?P<S>\d\d))?)? # hh:mm:ss
+ (?P<o>.+)? # 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
'''
return ' ' + str[1:]
return str
- def set(self, spec, offset=0, date_re=re.compile(r'''
- (((?P<y>\d\d\d\d)-)?((?P<m>\d\d?)-(?P<d>\d\d?))?)? # yyyy-mm-dd
- (?P<n>\.)? # .
- (((?P<H>\d?\d):(?P<M>\d\d))?(:(?P<S>\d\d))?)? # hh:mm:ss
- (?P<o>.+)? # 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 '<Date %s>'%self.__str__()
<Interval + 6m>
>>> Interval('1:00')/2
<Interval + 0:30>
+ >>> Interval('2003-03-18')
+ <Interval + [number of days between now and 2003-03-18]>
+ >>> Interval('-4d 2003-03-18')
+ <Interval + [number of days between now and 2003-03-14]>
Interval arithmetic is handled in a couple of special ways, trying
to cater for the most common cases. Fundamentally, Intervals which
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, \
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<s>[-+])? # + or -
+ \s*((?P<y>\d+\s*)y)? # year
+ \s*((?P<m>\d+\s*)m)? # month
+ \s*((?P<w>\d+\s*)w)? # week
+ \s*((?P<d>\d+\s*)d)? # day
+ \s*(((?P<H>\d+):(?P<M>\d+))?(:(?P<S>\d+))?)? # time
+ \s*(?P<D>
+ (\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<s>[+-])?1?(?P<y>([ ]{3}\d|\d{4}))(?P<m>\d{2})(?P<d>\d{2})
+ (?P<H>\d{2})(?P<M>\d{2})(?P<S>\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:
+ # we are always larger than None
return 1
for attr in 'sign year month day hour minute second'.split():
- if not hasattr(other, attr):
- return 1
r = cmp(getattr(self, attr), getattr(other, attr))
if r:
return r
d = seconds / 24
return Interval((sign, 0, 0, d, H, M, S))
- def set(self, spec, interval_re=re.compile('''
- \s*(?P<s>[-+])? # + or -
- \s*((?P<y>\d+\s*)y)? # year
- \s*((?P<m>\d+\s*)m)? # month
- \s*((?P<w>\d+\s*)w)? # week
- \s*((?P<d>\d+\s*)d)? # day
- \s*(((?P<H>\d+):(?P<M>\d+))?(:(?P<S>\d+))?)? # time
- \s*''', re.VERBOSE), serialised_re=re.compile('''
- (?P<s>[+-])?1?(?P<y>([ ]{3}\d|\d{4}))(?P<m>\d{2})(?P<d>\d{2})
- (?P<H>\d{2})(?P<M>\d{2})(?P<S>\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 '<Interval %s>'%self.__str__()
if self.sign < 0:
s = s + _(' ago')
else:
- s = _('in') + s
+ s = _('in ') + s
return s
def get_tuple(self):
<Range from None to 2003-03-09.20:00:00>
"""
- def __init__(self, spec, type, **params):
- """Initializes Range of type <type> from given <spec> string.
+ def __init__(self, spec, Type, allow_granularity=1, **params):
+ """Initializes Range of type <Type> from given <spec> 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
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)
return "<Range %s>" % 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")
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)`
print `Date(date) + Interval(interval)`
if __name__ == '__main__':
- test_range()
+ test()
# vim: set filetype=python ts=4 sw=4 et si