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.45 2003-03-06 06:12: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 addInterval(self, interval):
99 ''' Add the interval to this date, returning the date tuple
100 '''
101 # do the basic calc
102 sign = interval.sign
103 year = self.year + sign * interval.year
104 month = self.month + sign * interval.month
105 day = self.day + sign * interval.day
106 hour = self.hour + sign * interval.hour
107 minute = self.minute + sign * interval.minute
108 second = self.second + sign * interval.second
110 # now cope with under- and over-flow
111 # first do the time
112 while (second < 0 or second > 59 or minute < 0 or minute > 59 or
113 hour < 0 or hour > 59):
114 if second < 0: minute -= 1; second += 60
115 elif second > 59: minute += 1; second -= 60
116 if minute < 0: hour -= 1; minute += 60
117 elif minute > 59: hour += 1; minute -= 60
118 if hour < 0: day -= 1; hour += 24
119 elif hour > 59: day += 1; hour -= 24
121 # fix up the month so we're within range
122 while month < 1 or month > 12:
123 if month < 1: year -= 1; month += 12
124 if month > 12: year += 1; month -= 12
126 # now do the days, now that we know what month we're in
127 mdays = calendar.mdays
128 if month == 2 and calendar.isleap(year): month_days = 29
129 else: month_days = mdays[month]
130 while month < 1 or month > 12 or day < 0 or day > month_days:
131 # now to day under/over
132 if day < 0: month -= 1; day += month_days
133 elif day > month_days: month += 1; day -= month_days
135 # possibly fix up the month so we're within range
136 while month < 1 or month > 12:
137 if month < 1: year -= 1; month += 12
138 if month > 12: year += 1; month -= 12
140 # re-figure the number of days for this month
141 if month == 2 and calendar.isleap(year): month_days = 29
142 else: month_days = mdays[month]
143 return (year, month, day, hour, minute, second, 0, 0, 0)
145 def applyInterval(self, interval):
146 ''' Apply the interval to this date
147 '''
148 self.year, self.month, self.day, self.hour, self.minute, \
149 self.second, x, x, x = self.addInterval(interval)
151 def __add__(self, interval):
152 """Add an interval to this date to produce another date.
153 """
154 return Date(self.addInterval(interval))
156 # deviates from spec to allow subtraction of dates as well
157 def __sub__(self, other):
158 """ Subtract:
159 1. an interval from this date to produce another date.
160 2. a date from this date to produce an interval.
161 """
162 if isinstance(other, Interval):
163 other = Interval(other.get_tuple())
164 other.sign *= -1
165 return self.__add__(other)
167 assert isinstance(other, Date), 'May only subtract Dates or Intervals'
169 # TODO this code will fall over laughing if the dates cross
170 # leap years, phases of the moon, ....
171 a = calendar.timegm((self.year, self.month, self.day, self.hour,
172 self.minute, self.second, 0, 0, 0))
173 b = calendar.timegm((other.year, other.month, other.day,
174 other.hour, other.minute, other.second, 0, 0, 0))
175 diff = a - b
176 if diff < 0:
177 sign = 1
178 diff = -diff
179 else:
180 sign = -1
181 S = diff%60
182 M = (diff/60)%60
183 H = (diff/(60*60))%60
184 if H>1: S = 0
185 d = (diff/(24*60*60))%30
186 if d>1: H = S = M = 0
187 m = (diff/(30*24*60*60))%12
188 if m>1: H = S = M = 0
189 y = (diff/(365*24*60*60))
190 if y>1: d = H = S = M = 0
191 return Interval((y, m, d, H, M, S), sign=sign)
193 def __cmp__(self, other):
194 """Compare this date to another date."""
195 if other is None:
196 return 1
197 for attr in ('year', 'month', 'day', 'hour', 'minute', 'second'):
198 if not hasattr(other, attr):
199 return 1
200 r = cmp(getattr(self, attr), getattr(other, attr))
201 if r: return r
202 return 0
204 def __str__(self):
205 """Return this date as a string in the yyyy-mm-dd.hh:mm:ss format."""
206 return '%4d-%02d-%02d.%02d:%02d:%02d'%(self.year, self.month, self.day,
207 self.hour, self.minute, self.second)
209 def pretty(self, format='%d %B %Y'):
210 ''' print up the date date using a pretty format...
212 Note that if the day is zero, and the day appears first in the
213 format, then the day number will be removed from output.
214 '''
215 str = time.strftime(format, (self.year, self.month, self.day,
216 self.hour, self.minute, self.second, 0, 0, 0))
217 # handle zero day by removing it
218 if format.startswith('%d') and str[0] == '0':
219 return ' ' + str[1:]
220 return str
222 def set(self, spec, offset=0, date_re=re.compile(r'''
223 (((?P<y>\d\d\d\d)-)?((?P<m>\d\d?)-(?P<d>\d\d?))?)? # yyyy-mm-dd
224 (?P<n>\.)? # .
225 (((?P<H>\d?\d):(?P<M>\d\d))?(:(?P<S>\d\d))?)? # hh:mm:ss
226 (?P<o>.+)? # offset
227 ''', re.VERBOSE), serialised_re=re.compile(r'''
228 (\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)
229 ''', re.VERBOSE)):
230 ''' set the date to the value in spec
231 '''
232 m = serialised_re.match(spec)
233 if m is not None:
234 # we're serialised - easy!
235 self.year, self.month, self.day, self.hour, self.minute, \
236 self.second = map(int, m.groups()[:6])
237 return
239 # not serialised data, try usual format
240 m = date_re.match(spec)
241 if m is None:
242 raise ValueError, _('Not a date spec: [[yyyy-]mm-dd].'
243 '[[h]h:mm[:ss]][offset]')
245 info = m.groupdict()
247 # get the current date as our default
248 y,m,d,H,M,S,x,x,x = time.gmtime(time.time())
250 # override year, month, day parts
251 if info['m'] is not None and info['d'] is not None:
252 m = int(info['m'])
253 d = int(info['d'])
254 if info['y'] is not None:
255 y = int(info['y'])
256 # time defaults to 00:00:00 GMT - offset (local midnight)
257 H = -offset
258 M = S = 0
260 # override hour, minute, second parts
261 if info['H'] is not None and info['M'] is not None:
262 H = int(info['H']) - offset
263 M = int(info['M'])
264 S = 0
265 if info['S'] is not None: S = int(info['S'])
267 # now handle the adjustment of hour
268 ts = calendar.timegm((y,m,d,H,M,S,0,0,0))
269 self.year, self.month, self.day, self.hour, self.minute, \
270 self.second, x, x, x = time.gmtime(ts)
272 if info.get('o', None):
273 self.applyInterval(Interval(info['o']))
275 def __repr__(self):
276 return '<Date %s>'%self.__str__()
278 def local(self, offset):
279 """ Return this date as yyyy-mm-dd.hh:mm:ss in a local time zone.
280 """
281 return Date((self.year, self.month, self.day, self.hour + offset,
282 self.minute, self.second, 0, 0, 0))
284 def get_tuple(self):
285 return (self.year, self.month, self.day, self.hour, self.minute,
286 self.second, 0, 0, 0)
288 def serialise(self):
289 return '%4d%02d%02d%02d%02d%02d'%(self.year, self.month,
290 self.day, self.hour, self.minute, self.second)
292 class Interval:
293 '''
294 Date intervals are specified using the suffixes "y", "m", and "d". The
295 suffix "w" (for "week") means 7 days. Time intervals are specified in
296 hh:mm:ss format (the seconds may be omitted, but the hours and minutes
297 may not).
299 "3y" means three years
300 "2y 1m" means two years and one month
301 "1m 25d" means one month and 25 days
302 "2w 3d" means two weeks and three days
303 "1d 2:50" means one day, two hours, and 50 minutes
304 "14:00" means 14 hours
305 "0:04:33" means four minutes and 33 seconds
307 Example usage:
308 >>> Interval(" 3w 1 d 2:00")
309 <Interval + 22d 2:00>
310 >>> Date(". + 2d") + Interval("- 3w")
311 <Date 2000-06-07.00:34:02>
312 >>> Interval('1:59:59') + Interval('00:00:01')
313 <Interval + 2:00>
314 >>> Interval('2:00') + Interval('- 00:00:01')
315 <Interval + 1:59:59>
316 >>> Interval('1y')/2
317 <Interval + 6m>
318 >>> Interval('1:00')/2
319 <Interval + 0:30>
321 Interval arithmetic is handled in a couple of special ways, trying
322 to cater for the most common cases. Fundamentally, Intervals which
323 have both date and time parts will result in strange results in
324 arithmetic - because of the impossibility of handling day->month->year
325 over- and under-flows. Intervals may also be divided by some number.
327 Intervals are added to Dates in order of:
328 seconds, minutes, hours, years, months, days
330 Calculations involving months (eg '+2m') have no effect on days - only
331 days (or over/underflow from hours/mins/secs) will do that, and
332 days-per-month and leap years are accounted for. Leap seconds are not.
334 The interval format 'syyyymmddHHMMSS' (sign, year, month, day, hour,
335 minute, second) is the serialisation format returned by the serialise()
336 method, and is accepted as an argument on instatiation.
338 TODO: more examples, showing the order of addition operation
339 '''
340 def __init__(self, spec, sign=1):
341 """Construct an interval given a specification."""
342 if type(spec) == type(''):
343 self.set(spec)
344 else:
345 if len(spec) == 7:
346 self.sign, self.year, self.month, self.day, self.hour, \
347 self.minute, self.second = spec
348 else:
349 # old, buggy spec form
350 self.sign = sign
351 self.year, self.month, self.day, self.hour, self.minute, \
352 self.second = spec
354 def __cmp__(self, other):
355 """Compare this interval to another interval."""
356 if other is None:
357 return 1
358 for attr in 'sign year month day hour minute second'.split():
359 if not hasattr(other, attr):
360 return 1
361 r = cmp(getattr(self, attr), getattr(other, attr))
362 if r:
363 return r
364 return 0
366 def __str__(self):
367 """Return this interval as a string."""
368 l = []
369 if self.year: l.append('%sy'%self.year)
370 if self.month: l.append('%sm'%self.month)
371 if self.day: l.append('%sd'%self.day)
372 if self.second:
373 l.append('%d:%02d:%02d'%(self.hour, self.minute, self.second))
374 elif self.hour or self.minute:
375 l.append('%d:%02d'%(self.hour, self.minute))
376 if l:
377 l.insert(0, {1:'+', -1:'-'}[self.sign])
378 return ' '.join(l)
380 def __add__(self, other):
381 if isinstance(other, Date):
382 # the other is a Date - produce a Date
383 return Date(other.addInterval(self))
384 elif isinstance(other, Interval):
385 # add the other Interval to this one
386 a = self.get_tuple()
387 as = a[0]
388 b = other.get_tuple()
389 bs = b[0]
390 i = [as*x + bs*y for x,y in zip(a[1:],b[1:])]
391 i.insert(0, 1)
392 i = fixTimeOverflow(i)
393 return Interval(i)
394 # nope, no idea what to do with this other...
395 raise TypeError, "Can't add %r"%other
397 def __sub__(self, other):
398 if isinstance(other, Date):
399 # the other is a Date - produce a Date
400 interval = Interval(self.get_tuple())
401 interval.sign *= -1
402 return Date(other.addInterval(interval))
403 elif isinstance(other, Interval):
404 # add the other Interval to this one
405 a = self.get_tuple()
406 as = a[0]
407 b = other.get_tuple()
408 bs = b[0]
409 i = [as*x - bs*y for x,y in zip(a[1:],b[1:])]
410 i.insert(0, 1)
411 i = fixTimeOverflow(i)
412 return Interval(i)
413 # nope, no idea what to do with this other...
414 raise TypeError, "Can't add %r"%other
416 def __div__(self, other):
417 ''' Divide this interval by an int value.
419 Can't divide years and months sensibly in the _same_
420 calculation as days/time, so raise an error in that situation.
421 '''
422 try:
423 other = float(other)
424 except TypeError:
425 raise ValueError, "Can only divide Intervals by numbers"
427 y, m, d, H, M, S = (self.year, self.month, self.day,
428 self.hour, self.minute, self.second)
429 if y or m:
430 if d or H or M or S:
431 raise ValueError, "Can't divide Interval with date and time"
432 months = self.year*12 + self.month
433 months *= self.sign
435 months = int(months/other)
437 sign = months<0 and -1 or 1
438 m = months%12
439 y = months / 12
440 return Interval((sign, y, m, 0, 0, 0, 0))
442 else:
443 # handle a day/time division
444 seconds = S + M*60 + H*60*60 + d*60*60*24
445 seconds *= self.sign
447 seconds = int(seconds/other)
449 sign = seconds<0 and -1 or 1
450 seconds *= sign
451 S = seconds%60
452 seconds /= 60
453 M = seconds%60
454 seconds /= 60
455 H = seconds%24
456 d = seconds / 24
457 return Interval((sign, 0, 0, d, H, M, S))
459 def set(self, spec, interval_re=re.compile('''
460 \s*(?P<s>[-+])? # + or -
461 \s*((?P<y>\d+\s*)y)? # year
462 \s*((?P<m>\d+\s*)m)? # month
463 \s*((?P<w>\d+\s*)w)? # week
464 \s*((?P<d>\d+\s*)d)? # day
465 \s*(((?P<H>\d+):(?P<M>\d+))?(:(?P<S>\d+))?)? # time
466 \s*''', re.VERBOSE), serialised_re=re.compile('''
467 (?P<s>[+-])?1?(?P<y>([ ]{3}\d|\d{4}))(?P<m>\d{2})(?P<d>\d{2})
468 (?P<H>\d{2})(?P<M>\d{2})(?P<S>\d{2})''', re.VERBOSE)):
469 ''' set the date to the value in spec
470 '''
471 self.year = self.month = self.week = self.day = self.hour = \
472 self.minute = self.second = 0
473 self.sign = 1
474 m = serialised_re.match(spec)
475 if not m:
476 m = interval_re.match(spec)
477 if not m:
478 raise ValueError, _('Not an interval spec: [+-] [#y] [#m] [#w] '
479 '[#d] [[[H]H:MM]:SS]')
481 info = m.groupdict()
482 for group, attr in {'y':'year', 'm':'month', 'w':'week', 'd':'day',
483 'H':'hour', 'M':'minute', 'S':'second'}.items():
484 if info.get(group, None) is not None:
485 setattr(self, attr, int(info[group]))
487 if self.week:
488 self.day = self.day + self.week*7
490 if info['s'] is not None:
491 self.sign = {'+':1, '-':-1}[info['s']]
493 def __repr__(self):
494 return '<Interval %s>'%self.__str__()
496 def pretty(self):
497 ''' print up the date date using one of these nice formats..
498 '''
499 if self.year:
500 if self.year == 1:
501 return _('1 year')
502 else:
503 return _('%(number)s years')%{'number': self.year}
504 elif self.month or self.day > 13:
505 days = (self.month * 30) + self.day
506 if days > 28:
507 if int(days/30) > 1:
508 s = _('%(number)s months')%{'number': int(days/30)}
509 else:
510 s = _('1 month')
511 else:
512 s = _('%(number)s weeks')%{'number': int(days/7)}
513 elif self.day > 7:
514 s = _('1 week')
515 elif self.day > 1:
516 s = _('%(number)s days')%{'number': self.day}
517 elif self.day == 1 or self.hour > 12:
518 if self.sign > 0:
519 return _('tomorrow')
520 else:
521 return _('yesterday')
522 elif self.hour > 1:
523 s = _('%(number)s hours')%{'number': self.hour}
524 elif self.hour == 1:
525 if self.minute < 15:
526 s = _('an hour')
527 elif self.minute/15 == 2:
528 s = _('1 1/2 hours')
529 else:
530 s = _('1 %(number)s/4 hours')%{'number': self.minute/15}
531 elif self.minute < 1:
532 if self.sign > 0:
533 return _('in a moment')
534 else:
535 return _('just now')
536 elif self.minute == 1:
537 s = _('1 minute')
538 elif self.minute < 15:
539 s = _('%(number)s minutes')%{'number': self.minute}
540 elif int(self.minute/15) == 2:
541 s = _('1/2 an hour')
542 else:
543 s = _('%(number)s/4 hour')%{'number': int(self.minute/15)}
544 if self.sign < 0:
545 s = s + _(' ago')
546 else:
547 s = _('in') + s
548 return s
550 def get_tuple(self):
551 return (self.sign, self.year, self.month, self.day, self.hour,
552 self.minute, self.second)
554 def serialise(self):
555 sign = self.sign > 0 and '+' or '-'
556 return '%s%04d%02d%02d%02d%02d%02d'%(sign, self.year, self.month,
557 self.day, self.hour, self.minute, self.second)
559 def fixTimeOverflow(time):
560 ''' Handle the overflow in the time portion (H, M, S) of "time":
561 (sign, y,m,d,H,M,S)
563 Overflow and underflow will at most affect the _days_ portion of
564 the date. We do not overflow days to months as we don't know _how_
565 to, generally.
566 '''
567 # XXX we could conceivably use this function for handling regular dates
568 # XXX too - we just need to interrogate the month/year for the day
569 # XXX overflow...
571 sign, y, m, d, H, M, S = time
572 seconds = sign * (S + M*60 + H*60*60 + d*60*60*24)
573 if seconds:
574 sign = seconds<0 and -1 or 1
575 seconds *= sign
576 S = seconds%60
577 seconds /= 60
578 M = seconds%60
579 seconds /= 60
580 H = seconds%24
581 d = seconds / 24
582 else:
583 months = y*12 + m
584 sign = months<0 and -1 or 1
585 months *= sign
586 m = months%12
587 y = months/12
589 return (sign, y, m, d, H, M, S)
592 def test():
593 intervals = (" 3w 1 d 2:00", " + 2d", "3w")
594 for interval in intervals:
595 print '>>> Interval("%s")'%interval
596 print `Interval(interval)`
598 dates = (".", "2000-06-25.19:34:02", ". + 2d", "1997-04-17", "01-25",
599 "08-13.22:13", "14:25")
600 for date in dates:
601 print '>>> Date("%s")'%date
602 print `Date(date)`
604 sums = ((". + 2d", "3w"), (".", " 3w 1 d 2:00"))
605 for date, interval in sums:
606 print '>>> Date("%s") + Interval("%s")'%(date, interval)
607 print `Date(date) + Interval(interval)`
609 if __name__ == '__main__':
610 test()
612 # vim: set filetype=python ts=4 sw=4 et si