2654a03b665040455d71453581a28866a915c083
1 #
2 # Copyright (c) 2001 Bizar Software Pty Ltd (http://www.bizarsoftware.com.au/)
3 # This module is free software, and you may redistribute it and/or modify
4 # under the same terms as Python, so long as this copyright message and
5 # disclaimer are retained in their original form.
6 #
7 # IN NO EVENT SHALL BIZAR SOFTWARE PTY LTD BE LIABLE TO ANY PARTY FOR
8 # DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING
9 # OUT OF THE USE OF THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE
10 # POSSIBILITY OF SUCH DAMAGE.
11 #
12 # BIZAR SOFTWARE PTY LTD SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
13 # BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
14 # FOR A PARTICULAR PURPOSE. THE CODE PROVIDED HEREUNDER IS ON AN "AS IS"
15 # BASIS, AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,
16 # SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
17 #
18 # $Id: date.py,v 1.49 2003-03-19 03:25:30 richard Exp $
20 __doc__ = """
21 Date, time and time interval handling.
22 """
24 import time, re, calendar, types
25 from i18n import _
27 class Date:
28 '''
29 As strings, date-and-time stamps are specified with the date in
30 international standard format (yyyy-mm-dd) joined to the time
31 (hh:mm:ss) by a period ("."). Dates in this form can be easily compared
32 and are fairly readable when printed. An example of a valid stamp is
33 "2000-06-24.13:03:59". We'll call this the "full date format". When
34 Timestamp objects are printed as strings, they appear in the full date
35 format with the time always given in GMT. The full date format is
36 always exactly 19 characters long.
38 For user input, some partial forms are also permitted: the whole time
39 or just the seconds may be omitted; and the whole date may be omitted
40 or just the year may be omitted. If the time is given, the time is
41 interpreted in the user's local time zone. The Date constructor takes
42 care of these conversions. In the following examples, suppose that yyyy
43 is the current year, mm is the current month, and dd is the current day
44 of the month; and suppose that the user is on Eastern Standard Time.
46 "2000-04-17" means <Date 2000-04-17.00:00:00>
47 "01-25" means <Date yyyy-01-25.00:00:00>
48 "2000-04-17.03:45" means <Date 2000-04-17.08:45:00>
49 "08-13.22:13" means <Date yyyy-08-14.03:13:00>
50 "11-07.09:32:43" means <Date yyyy-11-07.14:32:43>
51 "14:25" means <Date yyyy-mm-dd.19:25:00>
52 "8:47:11" means <Date yyyy-mm-dd.13:47:11>
53 "." means "right now"
55 The Date class should understand simple date expressions of the form
56 stamp + interval and stamp - interval. When adding or subtracting
57 intervals involving months or years, the components are handled
58 separately. For example, when evaluating "2000-06-25 + 1m 10d", we
59 first add one month to get 2000-07-25, then add 10 days to get
60 2000-08-04 (rather than trying to decide whether 1m 10d means 38 or 40
61 or 41 days).
63 Example usage:
64 >>> Date(".")
65 <Date 2000-06-26.00:34:02>
66 >>> _.local(-5)
67 "2000-06-25.19:34:02"
68 >>> Date(". + 2d")
69 <Date 2000-06-28.00:34:02>
70 >>> Date("1997-04-17", -5)
71 <Date 1997-04-17.00:00:00>
72 >>> Date("01-25", -5)
73 <Date 2000-01-25.00:00:00>
74 >>> Date("08-13.22:13", -5)
75 <Date 2000-08-14.03:13:00>
76 >>> Date("14:25", -5)
77 <Date 2000-06-25.19:25:00>
79 The date format 'yyyymmddHHMMSS' (year, month, day, hour,
80 minute, second) is the serialisation format returned by the serialise()
81 method, and is accepted as an argument on instatiation.
82 '''
83 def __init__(self, spec='.', offset=0):
84 """Construct a date given a specification and a time zone offset.
86 'spec' is a full date or a partial form, with an optional
87 added or subtracted interval. Or a date 9-tuple.
88 'offset' is the local time zone offset from GMT in hours.
89 """
90 if type(spec) == type(''):
91 self.set(spec, offset=offset)
92 else:
93 y,m,d,H,M,S,x,x,x = spec
94 ts = calendar.timegm((y,m,d,H+offset,M,S,0,0,0))
95 self.year, self.month, self.day, self.hour, self.minute, \
96 self.second, x, x, x = time.gmtime(ts)
98 def set(self, spec, offset=0, date_re=re.compile(r'''
99 (((?P<y>\d\d\d\d)-)?(?P<m>\d\d?)?-(?P<d>\d\d?))? # [yyyy-]mm-dd
100 (?P<n>\.)? # .
101 (((?P<H>\d?\d):(?P<M>\d\d))?(:(?P<S>\d\d))?)? # hh:mm:ss
102 (?P<o>.+)? # offset
103 ''', re.VERBOSE), serialised_re=re.compile(r'''
104 (\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)
105 ''', re.VERBOSE)):
106 ''' set the date to the value in spec
107 '''
108 m = serialised_re.match(spec)
109 if m is not None:
110 # we're serialised - easy!
111 self.year, self.month, self.day, self.hour, self.minute, \
112 self.second = map(int, m.groups()[:6])
113 return
115 # not serialised data, try usual format
116 m = date_re.match(spec)
117 if m is None:
118 raise ValueError, _('Not a date spec: [[yyyy-]mm-dd].'
119 '[[h]h:mm[:ss]][offset]')
121 info = m.groupdict()
123 # get the current date as our default
124 y,m,d,H,M,S,x,x,x = time.gmtime(time.time())
126 # override year, month, day parts
127 if info['m'] is not None and info['d'] is not None:
128 m = int(info['m'])
129 d = int(info['d'])
130 if info['y'] is not None:
131 y = int(info['y'])
132 # time defaults to 00:00:00 GMT - offset (local midnight)
133 H = -offset
134 M = S = 0
136 # override hour, minute, second parts
137 if info['H'] is not None and info['M'] is not None:
138 H = int(info['H']) - offset
139 M = int(info['M'])
140 S = 0
141 if info['S'] is not None: S = int(info['S'])
143 # now handle the adjustment of hour
144 ts = calendar.timegm((y,m,d,H,M,S,0,0,0))
145 self.year, self.month, self.day, self.hour, self.minute, \
146 self.second, x, x, x = time.gmtime(ts)
148 if info.get('o', None):
149 try:
150 self.applyInterval(Interval(info['o']))
151 except ValueError:
152 raise ValueError, _('Not a date spec: [[yyyy-]mm-dd].'
153 '[[h]h:mm[:ss]][offset]')
155 def addInterval(self, interval):
156 ''' Add the interval to this date, returning the date tuple
157 '''
158 # do the basic calc
159 sign = interval.sign
160 year = self.year + sign * interval.year
161 month = self.month + sign * interval.month
162 day = self.day + sign * interval.day
163 hour = self.hour + sign * interval.hour
164 minute = self.minute + sign * interval.minute
165 second = self.second + sign * interval.second
167 # now cope with under- and over-flow
168 # first do the time
169 while (second < 0 or second > 59 or minute < 0 or minute > 59 or
170 hour < 0 or hour > 59):
171 if second < 0: minute -= 1; second += 60
172 elif second > 59: minute += 1; second -= 60
173 if minute < 0: hour -= 1; minute += 60
174 elif minute > 59: hour += 1; minute -= 60
175 if hour < 0: day -= 1; hour += 24
176 elif hour > 59: day += 1; hour -= 24
178 # fix up the month so we're within range
179 while month < 1 or month > 12:
180 if month < 1: year -= 1; month += 12
181 if month > 12: year += 1; month -= 12
183 # now do the days, now that we know what month we're in
184 mdays = calendar.mdays
185 if month == 2 and calendar.isleap(year): month_days = 29
186 else: month_days = mdays[month]
187 while month < 1 or month > 12 or day < 0 or day > month_days:
188 # now to day under/over
189 if day < 0: month -= 1; day += month_days
190 elif day > month_days: month += 1; day -= month_days
192 # possibly fix up the month so we're within range
193 while month < 1 or month > 12:
194 if month < 1: year -= 1; month += 12
195 if month > 12: year += 1; month -= 12
197 # re-figure the number of days for this month
198 if month == 2 and calendar.isleap(year): month_days = 29
199 else: month_days = mdays[month]
200 return (year, month, day, hour, minute, second, 0, 0, 0)
202 def applyInterval(self, interval):
203 ''' Apply the interval to this date
204 '''
205 self.year, self.month, self.day, self.hour, self.minute, \
206 self.second, x, x, x = self.addInterval(interval)
208 def __add__(self, interval):
209 """Add an interval to this date to produce another date.
210 """
211 return Date(self.addInterval(interval))
213 # deviates from spec to allow subtraction of dates as well
214 def __sub__(self, other):
215 """ Subtract:
216 1. an interval from this date to produce another date.
217 2. a date from this date to produce an interval.
218 """
219 if isinstance(other, Interval):
220 other = Interval(other.get_tuple())
221 other.sign *= -1
222 return self.__add__(other)
224 assert isinstance(other, Date), 'May only subtract Dates or Intervals'
226 # TODO this code will fall over laughing if the dates cross
227 # leap years, phases of the moon, ....
228 a = calendar.timegm((self.year, self.month, self.day, self.hour,
229 self.minute, self.second, 0, 0, 0))
230 b = calendar.timegm((other.year, other.month, other.day,
231 other.hour, other.minute, other.second, 0, 0, 0))
232 diff = a - b
233 if diff < 0:
234 sign = 1
235 diff = -diff
236 else:
237 sign = -1
238 S = diff%60
239 M = (diff/60)%60
240 H = (diff/(60*60))%60
241 if H>1: S = 0
242 d = (diff/(24*60*60))%30
243 if d>1: H = S = M = 0
244 m = (diff/(30*24*60*60))%12
245 if m>1: H = S = M = 0
246 y = (diff/(365*24*60*60))
247 if y>1: d = H = S = M = 0
248 return Interval((y, m, d, H, M, S), sign=sign)
250 def __cmp__(self, other):
251 """Compare this date to another date."""
252 if other is None:
253 return 1
254 for attr in ('year', 'month', 'day', 'hour', 'minute', 'second'):
255 if not hasattr(other, attr):
256 return 1
257 r = cmp(getattr(self, attr), getattr(other, attr))
258 if r: return r
259 return 0
261 def __str__(self):
262 """Return this date as a string in the yyyy-mm-dd.hh:mm:ss format."""
263 return '%4d-%02d-%02d.%02d:%02d:%02d'%(self.year, self.month, self.day,
264 self.hour, self.minute, self.second)
266 def pretty(self, format='%d %B %Y'):
267 ''' print up the date date using a pretty format...
269 Note that if the day is zero, and the day appears first in the
270 format, then the day number will be removed from output.
271 '''
272 str = time.strftime(format, (self.year, self.month, self.day,
273 self.hour, self.minute, self.second, 0, 0, 0))
274 # handle zero day by removing it
275 if format.startswith('%d') and str[0] == '0':
276 return ' ' + str[1:]
277 return str
279 def __repr__(self):
280 return '<Date %s>'%self.__str__()
282 def local(self, offset):
283 """ Return this date as yyyy-mm-dd.hh:mm:ss in a local time zone.
284 """
285 return Date((self.year, self.month, self.day, self.hour + offset,
286 self.minute, self.second, 0, 0, 0))
288 def get_tuple(self):
289 return (self.year, self.month, self.day, self.hour, self.minute,
290 self.second, 0, 0, 0)
292 def serialise(self):
293 return '%4d%02d%02d%02d%02d%02d'%(self.year, self.month,
294 self.day, self.hour, self.minute, self.second)
296 class Interval:
297 '''
298 Date intervals are specified using the suffixes "y", "m", and "d". The
299 suffix "w" (for "week") means 7 days. Time intervals are specified in
300 hh:mm:ss format (the seconds may be omitted, but the hours and minutes
301 may not).
303 "3y" means three years
304 "2y 1m" means two years and one month
305 "1m 25d" means one month and 25 days
306 "2w 3d" means two weeks and three days
307 "1d 2:50" means one day, two hours, and 50 minutes
308 "14:00" means 14 hours
309 "0:04:33" means four minutes and 33 seconds
311 Example usage:
312 >>> Interval(" 3w 1 d 2:00")
313 <Interval + 22d 2:00>
314 >>> Date(". + 2d") + Interval("- 3w")
315 <Date 2000-06-07.00:34:02>
316 >>> Interval('1:59:59') + Interval('00:00:01')
317 <Interval + 2:00>
318 >>> Interval('2:00') + Interval('- 00:00:01')
319 <Interval + 1:59:59>
320 >>> Interval('1y')/2
321 <Interval + 6m>
322 >>> Interval('1:00')/2
323 <Interval + 0:30>
325 Interval arithmetic is handled in a couple of special ways, trying
326 to cater for the most common cases. Fundamentally, Intervals which
327 have both date and time parts will result in strange results in
328 arithmetic - because of the impossibility of handling day->month->year
329 over- and under-flows. Intervals may also be divided by some number.
331 Intervals are added to Dates in order of:
332 seconds, minutes, hours, years, months, days
334 Calculations involving months (eg '+2m') have no effect on days - only
335 days (or over/underflow from hours/mins/secs) will do that, and
336 days-per-month and leap years are accounted for. Leap seconds are not.
338 The interval format 'syyyymmddHHMMSS' (sign, year, month, day, hour,
339 minute, second) is the serialisation format returned by the serialise()
340 method, and is accepted as an argument on instatiation.
342 TODO: more examples, showing the order of addition operation
343 '''
344 def __init__(self, spec, sign=1):
345 """Construct an interval given a specification."""
346 if type(spec) == type(''):
347 self.set(spec)
348 else:
349 if len(spec) == 7:
350 self.sign, self.year, self.month, self.day, self.hour, \
351 self.minute, self.second = spec
352 else:
353 # old, buggy spec form
354 self.sign = sign
355 self.year, self.month, self.day, self.hour, self.minute, \
356 self.second = spec
358 def set(self, spec, interval_re=re.compile('''
359 \s*(?P<s>[-+])? # + or -
360 \s*((?P<y>\d+\s*)y)? # year
361 \s*((?P<m>\d+\s*)m)? # month
362 \s*((?P<w>\d+\s*)w)? # week
363 \s*((?P<d>\d+\s*)d)? # day
364 \s*(((?P<H>\d+):(?P<M>\d+))?(:(?P<S>\d+))?)? # time
365 \s*''', re.VERBOSE), serialised_re=re.compile('''
366 (?P<s>[+-])?1?(?P<y>([ ]{3}\d|\d{4}))(?P<m>\d{2})(?P<d>\d{2})
367 (?P<H>\d{2})(?P<M>\d{2})(?P<S>\d{2})''', re.VERBOSE)):
368 ''' set the date to the value in spec
369 '''
370 self.year = self.month = self.week = self.day = self.hour = \
371 self.minute = self.second = 0
372 self.sign = 1
373 m = serialised_re.match(spec)
374 if not m:
375 m = interval_re.match(spec)
376 if not m:
377 raise ValueError, _('Not an interval spec: [+-] [#y] [#m] [#w] '
378 '[#d] [[[H]H:MM]:SS]')
380 info = m.groupdict()
381 valid = 0
382 for group, attr in {'y':'year', 'm':'month', 'w':'week', 'd':'day',
383 'H':'hour', 'M':'minute', 'S':'second'}.items():
384 if info.get(group, None) is not None:
385 valid = 1
386 setattr(self, attr, int(info[group]))
388 if not valid:
389 raise ValueError, _('Not an interval spec: [+-] [#y] [#m] [#w] '
390 '[#d] [[[H]H:MM]:SS]')
392 if self.week:
393 self.day = self.day + self.week*7
395 if info['s'] is not None:
396 self.sign = {'+':1, '-':-1}[info['s']]
398 def __cmp__(self, other):
399 """Compare this interval to another interval."""
400 if other is None:
401 # we are always larger than None
402 return 1
403 for attr in 'sign year month day hour minute second'.split():
404 r = cmp(getattr(self, attr), getattr(other, attr))
405 if r:
406 return r
407 return 0
409 def __str__(self):
410 """Return this interval as a string."""
411 l = []
412 if self.year: l.append('%sy'%self.year)
413 if self.month: l.append('%sm'%self.month)
414 if self.day: l.append('%sd'%self.day)
415 if self.second:
416 l.append('%d:%02d:%02d'%(self.hour, self.minute, self.second))
417 elif self.hour or self.minute:
418 l.append('%d:%02d'%(self.hour, self.minute))
419 if l:
420 l.insert(0, {1:'+', -1:'-'}[self.sign])
421 return ' '.join(l)
423 def __add__(self, other):
424 if isinstance(other, Date):
425 # the other is a Date - produce a Date
426 return Date(other.addInterval(self))
427 elif isinstance(other, Interval):
428 # add the other Interval to this one
429 a = self.get_tuple()
430 as = a[0]
431 b = other.get_tuple()
432 bs = b[0]
433 i = [as*x + bs*y for x,y in zip(a[1:],b[1:])]
434 i.insert(0, 1)
435 i = fixTimeOverflow(i)
436 return Interval(i)
437 # nope, no idea what to do with this other...
438 raise TypeError, "Can't add %r"%other
440 def __sub__(self, other):
441 if isinstance(other, Date):
442 # the other is a Date - produce a Date
443 interval = Interval(self.get_tuple())
444 interval.sign *= -1
445 return Date(other.addInterval(interval))
446 elif isinstance(other, Interval):
447 # add the other Interval to this one
448 a = self.get_tuple()
449 as = a[0]
450 b = other.get_tuple()
451 bs = b[0]
452 i = [as*x - bs*y for x,y in zip(a[1:],b[1:])]
453 i.insert(0, 1)
454 i = fixTimeOverflow(i)
455 return Interval(i)
456 # nope, no idea what to do with this other...
457 raise TypeError, "Can't add %r"%other
459 def __div__(self, other):
460 ''' Divide this interval by an int value.
462 Can't divide years and months sensibly in the _same_
463 calculation as days/time, so raise an error in that situation.
464 '''
465 try:
466 other = float(other)
467 except TypeError:
468 raise ValueError, "Can only divide Intervals by numbers"
470 y, m, d, H, M, S = (self.year, self.month, self.day,
471 self.hour, self.minute, self.second)
472 if y or m:
473 if d or H or M or S:
474 raise ValueError, "Can't divide Interval with date and time"
475 months = self.year*12 + self.month
476 months *= self.sign
478 months = int(months/other)
480 sign = months<0 and -1 or 1
481 m = months%12
482 y = months / 12
483 return Interval((sign, y, m, 0, 0, 0, 0))
485 else:
486 # handle a day/time division
487 seconds = S + M*60 + H*60*60 + d*60*60*24
488 seconds *= self.sign
490 seconds = int(seconds/other)
492 sign = seconds<0 and -1 or 1
493 seconds *= sign
494 S = seconds%60
495 seconds /= 60
496 M = seconds%60
497 seconds /= 60
498 H = seconds%24
499 d = seconds / 24
500 return Interval((sign, 0, 0, d, H, M, S))
502 def __repr__(self):
503 return '<Interval %s>'%self.__str__()
505 def pretty(self):
506 ''' print up the date date using one of these nice formats..
507 '''
508 if self.year:
509 if self.year == 1:
510 return _('1 year')
511 else:
512 return _('%(number)s years')%{'number': self.year}
513 elif self.month or self.day > 13:
514 days = (self.month * 30) + self.day
515 if days > 28:
516 if int(days/30) > 1:
517 s = _('%(number)s months')%{'number': int(days/30)}
518 else:
519 s = _('1 month')
520 else:
521 s = _('%(number)s weeks')%{'number': int(days/7)}
522 elif self.day > 7:
523 s = _('1 week')
524 elif self.day > 1:
525 s = _('%(number)s days')%{'number': self.day}
526 elif self.day == 1 or self.hour > 12:
527 if self.sign > 0:
528 return _('tomorrow')
529 else:
530 return _('yesterday')
531 elif self.hour > 1:
532 s = _('%(number)s hours')%{'number': self.hour}
533 elif self.hour == 1:
534 if self.minute < 15:
535 s = _('an hour')
536 elif self.minute/15 == 2:
537 s = _('1 1/2 hours')
538 else:
539 s = _('1 %(number)s/4 hours')%{'number': self.minute/15}
540 elif self.minute < 1:
541 if self.sign > 0:
542 return _('in a moment')
543 else:
544 return _('just now')
545 elif self.minute == 1:
546 s = _('1 minute')
547 elif self.minute < 15:
548 s = _('%(number)s minutes')%{'number': self.minute}
549 elif int(self.minute/15) == 2:
550 s = _('1/2 an hour')
551 else:
552 s = _('%(number)s/4 hour')%{'number': int(self.minute/15)}
553 if self.sign < 0:
554 s = s + _(' ago')
555 else:
556 s = _('in') + s
557 return s
559 def get_tuple(self):
560 return (self.sign, self.year, self.month, self.day, self.hour,
561 self.minute, self.second)
563 def serialise(self):
564 sign = self.sign > 0 and '+' or '-'
565 return '%s%04d%02d%02d%02d%02d%02d'%(sign, self.year, self.month,
566 self.day, self.hour, self.minute, self.second)
568 def fixTimeOverflow(time):
569 ''' Handle the overflow in the time portion (H, M, S) of "time":
570 (sign, y,m,d,H,M,S)
572 Overflow and underflow will at most affect the _days_ portion of
573 the date. We do not overflow days to months as we don't know _how_
574 to, generally.
575 '''
576 # XXX we could conceivably use this function for handling regular dates
577 # XXX too - we just need to interrogate the month/year for the day
578 # XXX overflow...
580 sign, y, m, d, H, M, S = time
581 seconds = sign * (S + M*60 + H*60*60 + d*60*60*24)
582 if seconds:
583 sign = seconds<0 and -1 or 1
584 seconds *= sign
585 S = seconds%60
586 seconds /= 60
587 M = seconds%60
588 seconds /= 60
589 H = seconds%24
590 d = seconds / 24
591 else:
592 months = y*12 + m
593 sign = months<0 and -1 or 1
594 months *= sign
595 m = months%12
596 y = months/12
598 return (sign, y, m, d, H, M, S)
600 class Range:
601 """
602 Represents range between two values
603 Ranges can be created using one of theese two alternative syntaxes:
605 1. Native english syntax:
606 [[From] <value>][ To <value>]
607 Keywords "From" and "To" are case insensitive. Keyword "From" is optional.
609 2. "Geek" syntax:
610 [<value>][; <value>]
612 Either first or second <value> can be omitted in both syntaxes.
614 Examples (consider local time is Sat Mar 8 22:07:48 EET 2003):
615 >>> Range("from 2-12 to 4-2")
616 <Range from 2003-02-12.00:00:00 to 2003-04-02.00:00:00>
618 >>> Range("18:00 TO +2m")
619 <Range from 2003-03-08.18:00:00 to 2003-05-08.20:07:48>
621 >>> Range("12:00")
622 <Range from 2003-03-08.12:00:00 to None>
624 >>> Range("tO +3d")
625 <Range from None to 2003-03-11.20:07:48>
627 >>> Range("2002-11-10; 2002-12-12")
628 <Range from 2002-11-10.00:00:00 to 2002-12-12.00:00:00>
630 >>> Range("; 20:00 +1d")
631 <Range from None to 2003-03-09.20:00:00>
633 """
634 def __init__(self, spec, Type, **params):
635 """Initializes Range of type <Type> from given <spec> string.
637 Sets two properties - from_value and to_value. None assigned to any of
638 this properties means "infinitum" (-infinitum to from_value and
639 +infinitum to to_value)
641 The Type parameter here should be class itself (e.g. Date), not a
642 class instance.
644 """
645 self.range_type = Type
646 re_range = r'(?:^|(?:from)?(.+?))(?:to(.+?)$|$)'
647 re_geek_range = r'(?:^|(.+?))(?:;(.+?)$|$)'
648 # Check which syntax to use
649 if spec.find(';') == -1:
650 # Native english
651 mch_range = re.search(re_range, spec.strip(), re.IGNORECASE)
652 else:
653 # Geek
654 mch_range = re.search(re_geek_range, spec.strip())
655 if mch_range:
656 self.from_value, self.to_value = mch_range.groups()
657 if self.from_value:
658 self.from_value = Type(self.from_value.strip(), **params)
659 if self.to_value:
660 self.to_value = Type(self.to_value.strip(), **params)
661 else:
662 raise ValueError, "Invalid range"
664 def __str__(self):
665 return "from %s to %s" % (self.from_value, self.to_value)
667 def __repr__(self):
668 return "<Range %s>" % self.__str__()
670 def test_range():
671 rspecs = ("from 2-12 to 4-2", "18:00 TO +2m", "12:00", "tO +3d",
672 "2002-11-10; 2002-12-12", "; 20:00 +1d")
673 for rspec in rspecs:
674 print '>>> Range("%s")' % rspec
675 print `Range(rspec, Date)`
676 print
678 def test():
679 intervals = (" 3w 1 d 2:00", " + 2d", "3w")
680 for interval in intervals:
681 print '>>> Interval("%s")'%interval
682 print `Interval(interval)`
684 dates = (".", "2000-06-25.19:34:02", ". + 2d", "1997-04-17", "01-25",
685 "08-13.22:13", "14:25")
686 for date in dates:
687 print '>>> Date("%s")'%date
688 print `Date(date)`
690 sums = ((". + 2d", "3w"), (".", " 3w 1 d 2:00"))
691 for date, interval in sums:
692 print '>>> Date("%s") + Interval("%s")'%(date, interval)
693 print `Date(date) + Interval(interval)`
695 if __name__ == '__main__':
696 test_range()
698 # vim: set filetype=python ts=4 sw=4 et si