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