Code

. fixed some problems in date calculations (calendar.py doesn't handle over-
[roundup.git] / roundup / date.py
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.19 2002-02-21 23:11:45 richard Exp $
20 __doc__ = """
21 Date, time and time interval handling.
22 """
24 import time, re, calendar
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>
78     '''
79     def __init__(self, spec='.', offset=0):
80         """Construct a date given a specification and a time zone offset.
82           'spec' is a full date or a partial form, with an optional
83                  added or subtracted interval. Or a date 9-tuple.
84         'offset' is the local time zone offset from GMT in hours.
85         """
86         if type(spec) == type(''):
87             self.set(spec, offset=offset)
88         else:
89             y,m,d,H,M,S,x,x,x = spec
90             ts = calendar.timegm((y,m,d,H+offset,M,S,0,0,0))
91             self.year, self.month, self.day, self.hour, self.minute, \
92                 self.second, x, x, x = time.gmtime(ts)
94     def applyInterval(self, interval):
95         ''' Apply the interval to this date
96         '''
97         t = (self.year + interval.year,
98              self.month + interval.month,
99              self.day + interval.day,
100              self.hour + interval.hour,
101              self.minute + interval.minute,
102              self.second + interval.second, 0, 0, 0)
103         self.year, self.month, self.day, self.hour, self.minute, \
104             self.second, x, x, x = time.gmtime(calendar.timegm(t))
106     def __add__(self, other):
107         """Add an interval to this date to produce another date.
108         """
109         # do the basic calc
110         sign = other.sign
111         year = self.year + sign * other.year
112         month = self.month + sign * other.month
113         day = self.day + sign * other.day
114         hour = self.hour + sign * other.hour
115         minute = self.minute + sign * other.minute
116         second = self.second + sign * other.second
118         # now cope with under- and over-flow
119         # first do the time
120         while (second < 0 or second > 59 or minute < 0 or minute > 59 or
121                 hour < 0 or hour > 59):
122             if second < 0: minute -= 1; second += 60
123             elif second > 59: minute += 1; second -= 60
124             if minute < 0: hour -= 1; minute += 60
125             elif minute > 59: hour += 1; minute -= 60
126             if hour < 0: day -= 1; hour += 60
127             elif hour > 59: day += 1; hour -= 60
129         # fix up the month so we're within range
130         while month < 1 or month > 12:
131             if month < 1: year -= 1; month += 12
132             if month > 12: year += 1; month -= 12
134         # now do the days, now that we know what month we're in
135         mdays = calendar.mdays
136         if month == 2 and calendar.isleap(year): month_days = 29
137         else: month_days = mdays[month]
138         while month < 1 or month > 12 or day < 0 or day > month_days:
139             # now to day under/over
140             if day < 0: month -= 1; day += month_days
141             elif day > month_days: month += 1; day -= month_days
143             # possibly fix up the month so we're within range
144             while month < 1 or month > 12:
145                 if month < 1: year -= 1; month += 12
146                 if month > 12: year += 1; month -= 12
148             # re-figure the number of days for this month
149             if month == 2 and calendar.isleap(year): month_days = 29
150             else: month_days = mdays[month]
152         return Date((year, month, day, hour, minute, second, 0, 0, 0))
154     # XXX deviates from spec to allow subtraction of dates as well
155     def __sub__(self, other):
156         """ Subtract:
157              1. an interval from this date to produce another date.
158              2. a date from this date to produce an interval.
159         """
160         if isinstance(other, Date):
161             # TODO this code will fall over laughing if the dates cross
162             # leap years, phases of the moon, ....
163             a = calendar.timegm((self.year, self.month, self.day, self.hour,
164                 self.minute, self.second, 0, 0, 0))
165             b = calendar.timegm((other.year, other.month, other.day,
166                 other.hour, other.minute, other.second, 0, 0, 0))
167             diff = a - b
168             if diff < 0:
169                 sign = 1
170                 diff = -diff
171             else:
172                 sign = -1
173             S = diff%60
174             M = (diff/60)%60
175             H = (diff/(60*60))%60
176             if H>1: S = 0
177             d = (diff/(24*60*60))%30
178             if d>1: H = S = M = 0
179             m = (diff/(30*24*60*60))%12
180             if m>1: H = S = M = 0
181             y = (diff/(365*24*60*60))
182             if y>1: d = H = S = M = 0
183             return Interval((y, m, d, H, M, S), sign=sign)
184         return self.__add__(other)
186     def __cmp__(self, other):
187         """Compare this date to another date."""
188         if other is None:
189             return 1
190         for attr in ('year', 'month', 'day', 'hour', 'minute', 'second'):
191             r = cmp(getattr(self, attr), getattr(other, attr))
192             if r: return r
193         return 0
195     def __str__(self):
196         """Return this date as a string in the yyyy-mm-dd.hh:mm:ss format."""
197         return '%4d-%02d-%02d.%02d:%02d:%02d'%(self.year, self.month, self.day,
198             self.hour, self.minute, self.second)
200     def pretty(self):
201         ''' print up the date date using a pretty format...
202         '''
203         str = time.strftime('%d %B %Y', (self.year, self.month,
204             self.day, self.hour, self.minute, self.second, 0, 0, 0))
205         if str[0] == '0': return ' ' + str[1:]
206         return str
208     def set(self, spec, offset=0, date_re=re.compile(r'''
209               (((?P<y>\d\d\d\d)-)?((?P<m>\d\d?)-(?P<d>\d\d?))?)? # yyyy-mm-dd
210               (?P<n>\.)?                                       # .
211               (((?P<H>\d?\d):(?P<M>\d\d))?(:(?P<S>\d\d))?)?    # hh:mm:ss
212               (?P<o>.+)?                                       # offset
213               ''', re.VERBOSE)):
214         ''' set the date to the value in spec
215         '''
216         m = date_re.match(spec)
217         if not m:
218             raise ValueError, _('Not a date spec: [[yyyy-]mm-dd].[[h]h:mm[:ss]]'
219                 '[offset]')
220         info = m.groupdict()
222         # get the current date/time using the offset
223         y,m,d,H,M,S,x,x,x = time.gmtime(time.time())
225         # override year, month, day parts
226         if info['m'] is not None and info['d'] is not None:
227             m = int(info['m'])
228             d = int(info['d'])
229             if info['y'] is not None: y = int(info['y'])
230             H = M = S = 0
232         # override hour, minute, second parts
233         if info['H'] is not None and info['M'] is not None:
234             H = int(info['H']) - offset
235             M = int(info['M'])
236             S = 0
237             if info['S'] is not None: S = int(info['S'])
239         # now handle the adjustment of hour
240         ts = calendar.timegm((y,m,d,H,M,S,0,0,0))
241         self.year, self.month, self.day, self.hour, self.minute, \
242             self.second, x, x, x = time.gmtime(ts)
244         if info['o']:
245             self.applyInterval(Interval(info['o']))
247     def __repr__(self):
248         return '<Date %s>'%self.__str__()
250     def local(self, offset):
251         """Return this date as yyyy-mm-dd.hh:mm:ss in a local time zone."""
252         t = (self.year, self.month, self.day, self.hour + offset, self.minute,
253              self.second, 0, 0, 0)
254         self.year, self.month, self.day, self.hour, self.minute, \
255             self.second, x, x, x = time.gmtime(calendar.timegm(t))
257     def get_tuple(self):
258         return (self.year, self.month, self.day, self.hour, self.minute,
259             self.second, 0, 0, 0)
261 class Interval:
262     '''
263     Date intervals are specified using the suffixes "y", "m", and "d". The
264     suffix "w" (for "week") means 7 days. Time intervals are specified in
265     hh:mm:ss format (the seconds may be omitted, but the hours and minutes
266     may not).
268       "3y" means three years
269       "2y 1m" means two years and one month
270       "1m 25d" means one month and 25 days
271       "2w 3d" means two weeks and three days
272       "1d 2:50" means one day, two hours, and 50 minutes
273       "14:00" means 14 hours
274       "0:04:33" means four minutes and 33 seconds
276     Example usage:
277         >>> Interval("  3w  1  d  2:00")
278         <Interval 22d 2:00>
279         >>> Date(". + 2d") + Interval("- 3w")
280         <Date 2000-06-07.00:34:02>
282     Intervals are added/subtracted in order of:
283        seconds, minutes, hours, years, months, days
285     Calculations involving monts (eg '+2m') have no effect on days - only
286     days (or over/underflow from hours/mins/secs) will do that, and
287     days-per-month and leap years are accounted for. Leap seconds are not.
289     TODO: more examples, showing the order of addition operation
290     '''
291     def __init__(self, spec, sign=1):
292         """Construct an interval given a specification."""
293         if type(spec) == type(''):
294             self.set(spec)
295         else:
296             self.sign = sign
297             self.year, self.month, self.day, self.hour, self.minute, \
298                 self.second = spec
300     def __cmp__(self, other):
301         """Compare this interval to another interval."""
302         if other is None:
303             return 1
304         for attr in ('year', 'month', 'day', 'hour', 'minute', 'second'):
305             r = cmp(getattr(self, attr), getattr(other, attr))
306             if r: return r
307         return 0
308         
309     def __str__(self):
310         """Return this interval as a string."""
311         sign = {1:'+', -1:'-'}[self.sign]
312         l = [sign]
313         if self.year: l.append('%sy'%self.year)
314         if self.month: l.append('%sm'%self.month)
315         if self.day: l.append('%sd'%self.day)
316         if self.second:
317             l.append('%d:%02d:%02d'%(self.hour, self.minute, self.second))
318         elif self.hour or self.minute:
319             l.append('%d:%02d'%(self.hour, self.minute))
320         return ' '.join(l)
322     def set(self, spec, interval_re = re.compile('''
323             \s*
324             (?P<s>[-+])?         # + or -
325             \s*
326             ((?P<y>\d+\s*)y)?    # year
327             \s*
328             ((?P<m>\d+\s*)m)?    # month
329             \s*
330             ((?P<w>\d+\s*)w)?    # week
331             \s*
332             ((?P<d>\d+\s*)d)?    # day
333             \s*
334             (((?P<H>\d+):(?P<M>\d+))?(:(?P<S>\d+))?)?   # time
335             \s*
336             ''', re.VERBOSE)):
337         ''' set the date to the value in spec
338         '''
339         self.year = self.month = self.week = self.day = self.hour = \
340             self.minute = self.second = 0
341         self.sign = 1
342         m = interval_re.match(spec)
343         if not m:
344             raise ValueError, _('Not an interval spec: [+-] [#y] [#m] [#w] '
345                 '[#d] [[[H]H:MM]:SS]')
347         info = m.groupdict()
348         for group, attr in {'y':'year', 'm':'month', 'w':'week', 'd':'day',
349                 'H':'hour', 'M':'minute', 'S':'second'}.items():
350             if info[group] is not None:
351                 setattr(self, attr, int(info[group]))
353         if self.week:
354             self.day = self.day + self.week*7
356         if info['s'] is not None:
357             self.sign = {'+':1, '-':-1}[info['s']]
359     def __repr__(self):
360         return '<Interval %s>'%self.__str__()
362     def pretty(self):
363         ''' print up the date date using one of these nice formats..
364         '''
365         if self.year or self.month > 2:
366             return None
367         elif self.month or self.day > 13:
368             days = (self.month * 30) + self.day
369             if days > 28:
370                 if int(days/30) > 1:
371                     s = _('%(number)s months')%{'number': int(days/30)}
372                 else:
373                     s = _('1 month')
374             else:
375                 s = _('%(number)s weeks')%{'number': int(days/7)}
376         elif self.day > 7:
377             s = _('1 week')
378         elif self.day > 1:
379             s = _('%(number)s days')%{'number': self.day}
380         elif self.day == 1 or self.hour > 12:
381             if self.sign > 0:
382                 return _('tomorrow')
383             else:
384                 return _('yesterday')
385         elif self.hour > 1:
386             s = _('%(number)s hours')%{'number': self.hour}
387         elif self.hour == 1:
388             if self.minute < 15:
389                 s = _('an hour')
390             elif self.minute/15 == 2:
391                 s = _('1 1/2 hours')
392             else:
393                 s = _('1 %(number)s/4 hours')%{'number': self.minute/15}
394         elif self.minute < 1:
395             if self.sign > 0:
396                 return _('in a moment')
397             else:
398                 return _('just now')
399         elif self.minute == 1:
400             s = _('1 minute')
401         elif self.minute < 15:
402             s = _('%(number)s minutes')%{'number': self.minute}
403         elif int(self.minute/15) == 2:
404             s = _('1/2 an hour')
405         else:
406             s = _('%(number)s/4 hour')%{'number': int(self.minute/15)}
407         return s
409     def get_tuple(self):
410         return (self.year, self.month, self.day, self.hour, self.minute,
411             self.second)
414 def test():
415     intervals = ("  3w  1  d  2:00", " + 2d", "3w")
416     for interval in intervals:
417         print '>>> Interval("%s")'%interval
418         print `Interval(interval)`
420     dates = (".", "2000-06-25.19:34:02", ". + 2d", "1997-04-17", "01-25",
421         "08-13.22:13", "14:25")
422     for date in dates:
423         print '>>> Date("%s")'%date
424         print `Date(date)`
426     sums = ((". + 2d", "3w"), (".", "  3w  1  d  2:00"))
427     for date, interval in sums:
428         print '>>> Date("%s") + Interval("%s")'%(date, interval)
429         print `Date(date) + Interval(interval)`
431 if __name__ == '__main__':
432     test()
435 # $Log: not supported by cvs2svn $
436 # Revision 1.18  2002/01/23 20:00:50  jhermann
437 # %e is a UNIXism and not documented for Python
439 # Revision 1.17  2002/01/16 07:02:57  richard
440 #  . lots of date/interval related changes:
441 #    - more relaxed date format for input
443 # Revision 1.16  2002/01/08 11:56:24  richard
444 # missed an import _
446 # Revision 1.15  2002/01/05 02:27:00  richard
447 # I18N'ification
449 # Revision 1.14  2001/11/22 15:46:42  jhermann
450 # Added module docstrings to all modules.
452 # Revision 1.13  2001/09/18 22:58:37  richard
454 # Added some more help to roundu-admin
456 # Revision 1.12  2001/08/17 03:08:11  richard
457 # fixed prettification of intervals of 1 week
459 # Revision 1.11  2001/08/15 23:43:18  richard
460 # Fixed some isFooTypes that I missed.
461 # Refactored some code in the CGI code.
463 # Revision 1.10  2001/08/07 00:24:42  richard
464 # stupid typo
466 # Revision 1.9  2001/08/07 00:15:51  richard
467 # Added the copyright/license notice to (nearly) all files at request of
468 # Bizar Software.
470 # Revision 1.8  2001/08/05 07:46:12  richard
471 # Changed date.Date to use regular string formatting instead of strftime -
472 # win32 seems to have problems with %T and no hour... or something...
474 # Revision 1.7  2001/08/02 00:27:04  richard
475 # Extended the range of intervals that are pretty-printed before actual dates
476 # are displayed.
478 # Revision 1.6  2001/07/31 09:54:18  richard
479 # Fixed the 2.1-specific gmtime() (no arg) call in roundup.date. (Paul Wright)
481 # Revision 1.5  2001/07/29 07:01:39  richard
482 # Added vim command to all source so that we don't get no steenkin' tabs :)
484 # Revision 1.4  2001/07/25 04:09:34  richard
485 # Fixed offset handling (shoulda read the spec a little better)
487 # Revision 1.3  2001/07/23 07:56:05  richard
488 # Storing only marshallable data in the db - no nasty pickled class references.
490 # Revision 1.2  2001/07/22 12:09:32  richard
491 # Final commit of Grande Splite
493 # Revision 1.1  2001/07/22 11:58:35  richard
494 # More Grande Splite
497 # vim: set filetype=python ts=4 sw=4 et si