Code

%e is a UNIXism and not documented for Python
[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.18 2002-01-23 20:00:50 jhermann 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         t = (self.year + other.sign * other.year,
109             self.month + other.sign * other.month,
110             self.day + other.sign * other.day,
111             self.hour + other.sign * other.hour,
112             self.minute + other.sign * other.minute,
113             self.second + other.sign * other.second, 0, 0, 0)
114         return Date(time.gmtime(calendar.timegm(t)))
116     # XXX deviates from spec to allow subtraction of dates as well
117     def __sub__(self, other):
118         """ Subtract:
119              1. an interval from this date to produce another date.
120              2. a date from this date to produce an interval.
121         """
122         if isinstance(other, Date):
123             # TODO this code will fall over laughing if the dates cross
124             # leap years, phases of the moon, ....
125             a = calendar.timegm((self.year, self.month, self.day, self.hour,
126                 self.minute, self.second, 0, 0, 0))
127             b = calendar.timegm((other.year, other.month, other.day, other.hour,
128                 other.minute, other.second, 0, 0, 0))
129             diff = a - b
130             if diff < 0:
131                 sign = -1
132                 diff = -diff
133             else:
134                 sign = 1
135             S = diff%60
136             M = (diff/60)%60
137             H = (diff/(60*60))%60
138             if H>1: S = 0
139             d = (diff/(24*60*60))%30
140             if d>1: H = S = M = 0
141             m = (diff/(30*24*60*60))%12
142             if m>1: H = S = M = 0
143             y = (diff/(365*24*60*60))
144             if y>1: d = H = S = M = 0
145             return Interval((y, m, d, H, M, S), sign=sign)
146         t = (self.year - other.sign * other.year,
147              self.month - other.sign * other.month,
148              self.day - other.sign * other.day,
149              self.hour - other.sign * other.hour,
150              self.minute - other.sign * other.minute,
151              self.second - other.sign * other.second, 0, 0, 0)
152         return Date(time.gmtime(calendar.timegm(t)))
154     def __cmp__(self, other):
155         """Compare this date to another date."""
156         if other is None:
157             return 1
158         for attr in ('year', 'month', 'day', 'hour', 'minute', 'second'):
159             r = cmp(getattr(self, attr), getattr(other, attr))
160             if r: return r
161         return 0
163     def __str__(self):
164         """Return this date as a string in the yyyy-mm-dd.hh:mm:ss format."""
165         return '%4d-%02d-%02d.%02d:%02d:%02d'%(self.year, self.month, self.day,
166             self.hour, self.minute, self.second)
168     def pretty(self):
169         ''' print up the date date using a pretty format...
170         '''
171         str = time.strftime('%d %B %Y', (self.year, self.month,
172             self.day, self.hour, self.minute, self.second, 0, 0, 0))
173         if str[0] == '0': return ' ' + str[1:]
174         return str
176     def set(self, spec, offset=0, date_re=re.compile(r'''
177               (((?P<y>\d\d\d\d)-)?((?P<m>\d\d?)-(?P<d>\d\d?))?)? # yyyy-mm-dd
178               (?P<n>\.)?                                       # .
179               (((?P<H>\d?\d):(?P<M>\d\d))?(:(?P<S>\d\d))?)?    # hh:mm:ss
180               (?P<o>.+)?                                       # offset
181               ''', re.VERBOSE)):
182         ''' set the date to the value in spec
183         '''
184         m = date_re.match(spec)
185         if not m:
186             raise ValueError, _('Not a date spec: [[yyyy-]mm-dd].[[h]h:mm[:ss]]'
187                 '[offset]')
188         info = m.groupdict()
190         # get the current date/time using the offset
191         y,m,d,H,M,S,x,x,x = time.gmtime(time.time())
193         # override year, month, day parts
194         if info['m'] is not None and info['d'] is not None:
195             m = int(info['m'])
196             d = int(info['d'])
197             if info['y'] is not None: y = int(info['y'])
198             H = M = S = 0
200         # override hour, minute, second parts
201         if info['H'] is not None and info['M'] is not None:
202             H = int(info['H']) - offset
203             M = int(info['M'])
204             S = 0
205             if info['S'] is not None: S = int(info['S'])
207         # now handle the adjustment of hour
208         ts = calendar.timegm((y,m,d,H,M,S,0,0,0))
209         self.year, self.month, self.day, self.hour, self.minute, \
210             self.second, x, x, x = time.gmtime(ts)
212         if info['o']:
213             self.applyInterval(Interval(info['o']))
215     def __repr__(self):
216         return '<Date %s>'%self.__str__()
218     def local(self, offset):
219         """Return this date as yyyy-mm-dd.hh:mm:ss in a local time zone."""
220         t = (self.year, self.month, self.day, self.hour + offset, self.minute,
221              self.second, 0, 0, 0)
222         self.year, self.month, self.day, self.hour, self.minute, \
223             self.second, x, x, x = time.gmtime(calendar.timegm(t))
225     def get_tuple(self):
226         return (self.year, self.month, self.day, self.hour, self.minute,
227             self.second, 0, 0, 0)
229 class Interval:
230     '''
231     Date intervals are specified using the suffixes "y", "m", and "d". The
232     suffix "w" (for "week") means 7 days. Time intervals are specified in
233     hh:mm:ss format (the seconds may be omitted, but the hours and minutes
234     may not).
236       "3y" means three years
237       "2y 1m" means two years and one month
238       "1m 25d" means one month and 25 days
239       "2w 3d" means two weeks and three days
240       "1d 2:50" means one day, two hours, and 50 minutes
241       "14:00" means 14 hours
242       "0:04:33" means four minutes and 33 seconds
244     Example usage:
245         >>> Interval("  3w  1  d  2:00")
246         <Interval 22d 2:00>
247         >>> Date(". + 2d") - Interval("3w")
248         <Date 2000-06-07.00:34:02>
249     '''
250     def __init__(self, spec, sign=1):
251         """Construct an interval given a specification."""
252         if type(spec) == type(''):
253             self.set(spec)
254         else:
255             self.sign = sign
256             self.year, self.month, self.day, self.hour, self.minute, \
257                 self.second = spec
259     def __cmp__(self, other):
260         """Compare this interval to another interval."""
261         if other is None:
262             return 1
263         for attr in ('year', 'month', 'day', 'hour', 'minute', 'second'):
264             r = cmp(getattr(self, attr), getattr(other, attr))
265             if r: return r
266         return 0
267         
268     def __str__(self):
269         """Return this interval as a string."""
270         sign = {1:'+', -1:'-'}[self.sign]
271         l = [sign]
272         if self.year: l.append('%sy'%self.year)
273         if self.month: l.append('%sm'%self.month)
274         if self.day: l.append('%sd'%self.day)
275         if self.second:
276             l.append('%d:%02d:%02d'%(self.hour, self.minute, self.second))
277         elif self.hour or self.minute:
278             l.append('%d:%02d'%(self.hour, self.minute))
279         return ' '.join(l)
281     def set(self, spec, interval_re = re.compile('''
282             \s*
283             (?P<s>[-+])?         # + or -
284             \s*
285             ((?P<y>\d+\s*)y)?    # year
286             \s*
287             ((?P<m>\d+\s*)m)?    # month
288             \s*
289             ((?P<w>\d+\s*)w)?    # week
290             \s*
291             ((?P<d>\d+\s*)d)?    # day
292             \s*
293             (((?P<H>\d?\d):(?P<M>\d\d))?(:(?P<S>\d\d))?)?   # time
294             \s*
295             ''', re.VERBOSE)):
296         ''' set the date to the value in spec
297         '''
298         self.year = self.month = self.week = self.day = self.hour = \
299             self.minute = self.second = 0
300         self.sign = 1
301         m = interval_re.match(spec)
302         if not m:
303             raise ValueError, _('Not an interval spec: [+-] [#y] [#m] [#w] '
304                 '[#d] [[[H]H:MM]:SS]')
306         info = m.groupdict()
307         for group, attr in {'y':'year', 'm':'month', 'w':'week', 'd':'day',
308                 'H':'hour', 'M':'minute', 'S':'second'}.items():
309             if info[group] is not None:
310                 setattr(self, attr, int(info[group]))
312         if self.week:
313             self.day = self.day + self.week*7
315         if info['s'] is not None:
316             self.sign = {'+':1, '-':-1}[info['s']]
318     def __repr__(self):
319         return '<Interval %s>'%self.__str__()
321     def pretty(self):
322         ''' print up the date date using one of these nice formats..
323         '''
324         if self.year or self.month > 2:
325             return None
326         if self.month or self.day > 13:
327             days = (self.month * 30) + self.day
328             if days > 28:
329                 if int(days/30) > 1:
330                     return _('%(number)s months')%{'number': int(days/30)}
331                 else:
332                     return _('1 month')
333             else:
334                 return _('%(number)s weeks')%{'number': int(days/7)}
335         if self.day > 7:
336             return _('1 week')
337         if self.day > 1:
338             return _('%(number)s days')%{'number': self.day}
339         if self.day == 1 or self.hour > 12:
340             return _('yesterday')
341         if self.hour > 1:
342             return _('%(number)s hours')%{'number': self.hour}
343         if self.hour == 1:
344             if self.minute < 15:
345                 return _('an hour')
346             quart = self.minute/15
347             if quart == 2:
348                 return _('1 1/2 hours')
349             return _('1 %(number)s/4 hours')%{'number': quart}
350         if self.minute < 1:
351             return _('just now')
352         if self.minute == 1:
353             return _('1 minute')
354         if self.minute < 15:
355             return _('%(number)s minutes')%{'number': self.minute}
356         quart = int(self.minute/15)
357         if quart == 2:
358             return _('1/2 an hour')
359         return _('%(number)s/4 hour')%{'number': quart}
361     def get_tuple(self):
362         return (self.year, self.month, self.day, self.hour, self.minute,
363             self.second)
366 def test():
367     intervals = ("  3w  1  d  2:00", " + 2d", "3w")
368     for interval in intervals:
369         print '>>> Interval("%s")'%interval
370         print `Interval(interval)`
372     dates = (".", "2000-06-25.19:34:02", ". + 2d", "1997-04-17", "01-25",
373         "08-13.22:13", "14:25")
374     for date in dates:
375         print '>>> Date("%s")'%date
376         print `Date(date)`
378     sums = ((". + 2d", "3w"), (".", "  3w  1  d  2:00"))
379     for date, interval in sums:
380         print '>>> Date("%s") + Interval("%s")'%(date, interval)
381         print `Date(date) + Interval(interval)`
383 if __name__ == '__main__':
384     test()
387 # $Log: not supported by cvs2svn $
388 # Revision 1.17  2002/01/16 07:02:57  richard
389 #  . lots of date/interval related changes:
390 #    - more relaxed date format for input
392 # Revision 1.16  2002/01/08 11:56:24  richard
393 # missed an import _
395 # Revision 1.15  2002/01/05 02:27:00  richard
396 # I18N'ification
398 # Revision 1.14  2001/11/22 15:46:42  jhermann
399 # Added module docstrings to all modules.
401 # Revision 1.13  2001/09/18 22:58:37  richard
403 # Added some more help to roundu-admin
405 # Revision 1.12  2001/08/17 03:08:11  richard
406 # fixed prettification of intervals of 1 week
408 # Revision 1.11  2001/08/15 23:43:18  richard
409 # Fixed some isFooTypes that I missed.
410 # Refactored some code in the CGI code.
412 # Revision 1.10  2001/08/07 00:24:42  richard
413 # stupid typo
415 # Revision 1.9  2001/08/07 00:15:51  richard
416 # Added the copyright/license notice to (nearly) all files at request of
417 # Bizar Software.
419 # Revision 1.8  2001/08/05 07:46:12  richard
420 # Changed date.Date to use regular string formatting instead of strftime -
421 # win32 seems to have problems with %T and no hour... or something...
423 # Revision 1.7  2001/08/02 00:27:04  richard
424 # Extended the range of intervals that are pretty-printed before actual dates
425 # are displayed.
427 # Revision 1.6  2001/07/31 09:54:18  richard
428 # Fixed the 2.1-specific gmtime() (no arg) call in roundup.date. (Paul Wright)
430 # Revision 1.5  2001/07/29 07:01:39  richard
431 # Added vim command to all source so that we don't get no steenkin' tabs :)
433 # Revision 1.4  2001/07/25 04:09:34  richard
434 # Fixed offset handling (shoulda read the spec a little better)
436 # Revision 1.3  2001/07/23 07:56:05  richard
437 # Storing only marshallable data in the db - no nasty pickled class references.
439 # Revision 1.2  2001/07/22 12:09:32  richard
440 # Final commit of Grande Splite
442 # Revision 1.1  2001/07/22 11:58:35  richard
443 # More Grande Splite
446 # vim: set filetype=python ts=4 sw=4 et si