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.13 2001-09-18 22:58:37 richard Exp $
20 import time, re, calendar
22 class Date:
23 '''
24 As strings, date-and-time stamps are specified with the date in
25 international standard format (yyyy-mm-dd) joined to the time
26 (hh:mm:ss) by a period ("."). Dates in this form can be easily compared
27 and are fairly readable when printed. An example of a valid stamp is
28 "2000-06-24.13:03:59". We'll call this the "full date format". When
29 Timestamp objects are printed as strings, they appear in the full date
30 format with the time always given in GMT. The full date format is
31 always exactly 19 characters long.
33 For user input, some partial forms are also permitted: the whole time
34 or just the seconds may be omitted; and the whole date may be omitted
35 or just the year may be omitted. If the time is given, the time is
36 interpreted in the user's local time zone. The Date constructor takes
37 care of these conversions. In the following examples, suppose that yyyy
38 is the current year, mm is the current month, and dd is the current day
39 of the month; and suppose that the user is on Eastern Standard Time.
41 "2000-04-17" means <Date 2000-04-17.00:00:00>
42 "01-25" means <Date yyyy-01-25.00:00:00>
43 "2000-04-17.03:45" means <Date 2000-04-17.08:45:00>
44 "08-13.22:13" means <Date yyyy-08-14.03:13:00>
45 "11-07.09:32:43" means <Date yyyy-11-07.14:32:43>
46 "14:25" means <Date yyyy-mm-dd.19:25:00>
47 "8:47:11" means <Date yyyy-mm-dd.13:47:11>
48 "." means "right now"
50 The Date class should understand simple date expressions of the form
51 stamp + interval and stamp - interval. When adding or subtracting
52 intervals involving months or years, the components are handled
53 separately. For example, when evaluating "2000-06-25 + 1m 10d", we
54 first add one month to get 2000-07-25, then add 10 days to get
55 2000-08-04 (rather than trying to decide whether 1m 10d means 38 or 40
56 or 41 days).
58 Example usage:
59 >>> Date(".")
60 <Date 2000-06-26.00:34:02>
61 >>> _.local(-5)
62 "2000-06-25.19:34:02"
63 >>> Date(". + 2d")
64 <Date 2000-06-28.00:34:02>
65 >>> Date("1997-04-17", -5)
66 <Date 1997-04-17.00:00:00>
67 >>> Date("01-25", -5)
68 <Date 2000-01-25.00:00:00>
69 >>> Date("08-13.22:13", -5)
70 <Date 2000-08-14.03:13:00>
71 >>> Date("14:25", -5)
72 <Date 2000-06-25.19:25:00>
73 '''
74 def __init__(self, spec='.', offset=0):
75 """Construct a date given a specification and a time zone offset.
77 'spec' is a full date or a partial form, with an optional
78 added or subtracted interval. Or a date 9-tuple.
79 'offset' is the local time zone offset from GMT in hours.
80 """
81 if type(spec) == type(''):
82 self.set(spec, offset=offset)
83 else:
84 y,m,d,H,M,S,x,x,x = spec
85 ts = calendar.timegm((y,m,d,H+offset,M,S,0,0,0))
86 self.year, self.month, self.day, self.hour, self.minute, \
87 self.second, x, x, x = time.gmtime(ts)
89 def applyInterval(self, interval):
90 ''' Apply the interval to this date
91 '''
92 t = (self.year + interval.year,
93 self.month + interval.month,
94 self.day + interval.day,
95 self.hour + interval.hour,
96 self.minute + interval.minute,
97 self.second + interval.second, 0, 0, 0)
98 self.year, self.month, self.day, self.hour, self.minute, \
99 self.second, x, x, x = time.gmtime(calendar.timegm(t))
101 def __add__(self, other):
102 """Add an interval to this date to produce another date."""
103 t = (self.year + other.sign * other.year,
104 self.month + other.sign * other.month,
105 self.day + other.sign * other.day,
106 self.hour + other.sign * other.hour,
107 self.minute + other.sign * other.minute,
108 self.second + other.sign * other.second, 0, 0, 0)
109 return Date(time.gmtime(calendar.timegm(t)))
111 # XXX deviates from spec to allow subtraction of dates as well
112 def __sub__(self, other):
113 """ Subtract:
114 1. an interval from this date to produce another date.
115 2. a date from this date to produce an interval.
116 """
117 if isinstance(other, Date):
118 # TODO this code will fall over laughing if the dates cross
119 # leap years, phases of the moon, ....
120 a = calendar.timegm((self.year, self.month, self.day, self.hour,
121 self.minute, self.second, 0, 0, 0))
122 b = calendar.timegm((other.year, other.month, other.day, other.hour,
123 other.minute, other.second, 0, 0, 0))
124 diff = a - b
125 if diff < 0:
126 sign = -1
127 diff = -diff
128 else:
129 sign = 1
130 S = diff%60
131 M = (diff/60)%60
132 H = (diff/(60*60))%60
133 if H>1: S = 0
134 d = (diff/(24*60*60))%30
135 if d>1: H = S = M = 0
136 m = (diff/(30*24*60*60))%12
137 if m>1: H = S = M = 0
138 y = (diff/(365*24*60*60))
139 if y>1: d = H = S = M = 0
140 return Interval((y, m, d, H, M, S), sign=sign)
141 t = (self.year - other.sign * other.year,
142 self.month - other.sign * other.month,
143 self.day - other.sign * other.day,
144 self.hour - other.sign * other.hour,
145 self.minute - other.sign * other.minute,
146 self.second - other.sign * other.second, 0, 0, 0)
147 return Date(time.gmtime(calendar.timegm(t)))
149 def __cmp__(self, other):
150 """Compare this date to another date."""
151 for attr in ('year', 'month', 'day', 'hour', 'minute', 'second'):
152 r = cmp(getattr(self, attr), getattr(other, attr))
153 if r: return r
154 return 0
156 def __str__(self):
157 """Return this date as a string in the yyyy-mm-dd.hh:mm:ss format."""
158 return '%4d-%02d-%02d.%02d:%02d:%02d'%(self.year, self.month, self.day,
159 self.hour, self.minute, self.second)
161 def pretty(self):
162 ''' print up the date date using a pretty format...
163 '''
164 return time.strftime('%e %B %Y', (self.year, self.month,
165 self.day, self.hour, self.minute, self.second, 0, 0, 0))
167 def set(self, spec, offset=0, date_re=re.compile(r'''
168 (((?P<y>\d\d\d\d)-)?((?P<m>\d\d)-(?P<d>\d\d))?)? # yyyy-mm-dd
169 (?P<n>\.)? # .
170 (((?P<H>\d?\d):(?P<M>\d\d))?(:(?P<S>\d\d))?)? # hh:mm:ss
171 (?P<o>.+)? # offset
172 ''', re.VERBOSE)):
173 ''' set the date to the value in spec
174 '''
175 m = date_re.match(spec)
176 if not m:
177 raise ValueError, 'Not a date spec: [[yyyy-]mm-dd].[[h]h:mm[:ss]] [offset]'
178 info = m.groupdict()
180 # get the current date/time using the offset
181 y,m,d,H,M,S,x,x,x = time.gmtime(time.time())
183 # override year, month, day parts
184 if info['m'] is not None and info['d'] is not None:
185 m = int(info['m'])
186 d = int(info['d'])
187 if info['y'] is not None: y = int(info['y'])
188 H = M = S = 0
190 # override hour, minute, second parts
191 if info['H'] is not None and info['M'] is not None:
192 H = int(info['H']) - offset
193 M = int(info['M'])
194 S = 0
195 if info['S'] is not None: S = int(info['S'])
197 # now handle the adjustment of hour
198 ts = calendar.timegm((y,m,d,H,M,S,0,0,0))
199 self.year, self.month, self.day, self.hour, self.minute, \
200 self.second, x, x, x = time.gmtime(ts)
202 if info['o']:
203 self.applyInterval(Interval(info['o']))
205 def __repr__(self):
206 return '<Date %s>'%self.__str__()
208 def local(self, offset):
209 """Return this date as yyyy-mm-dd.hh:mm:ss in a local time zone."""
210 t = (self.year, self.month, self.day, self.hour + offset, self.minute,
211 self.second, 0, 0, 0)
212 self.year, self.month, self.day, self.hour, self.minute, \
213 self.second, x, x, x = time.gmtime(calendar.timegm(t))
215 def get_tuple(self):
216 return (self.year, self.month, self.day, self.hour, self.minute,
217 self.second, 0, 0, 0)
219 class Interval:
220 '''
221 Date intervals are specified using the suffixes "y", "m", and "d". The
222 suffix "w" (for "week") means 7 days. Time intervals are specified in
223 hh:mm:ss format (the seconds may be omitted, but the hours and minutes
224 may not).
226 "3y" means three years
227 "2y 1m" means two years and one month
228 "1m 25d" means one month and 25 days
229 "2w 3d" means two weeks and three days
230 "1d 2:50" means one day, two hours, and 50 minutes
231 "14:00" means 14 hours
232 "0:04:33" means four minutes and 33 seconds
234 Example usage:
235 >>> Interval(" 3w 1 d 2:00")
236 <Interval 22d 2:00>
237 >>> Date(". + 2d") - Interval("3w")
238 <Date 2000-06-07.00:34:02>
239 '''
240 def __init__(self, spec, sign=1):
241 """Construct an interval given a specification."""
242 if type(spec) == type(''):
243 self.set(spec)
244 else:
245 self.sign = sign
246 self.year, self.month, self.day, self.hour, self.minute, \
247 self.second = spec
249 def __cmp__(self, other):
250 """Compare this interval to another interval."""
251 for attr in ('year', 'month', 'day', 'hour', 'minute', 'second'):
252 r = cmp(getattr(self, attr), getattr(other, attr))
253 if r: return r
254 return 0
256 def __str__(self):
257 """Return this interval as a string."""
258 sign = {1:'+', -1:'-'}[self.sign]
259 l = [sign]
260 if self.year: l.append('%sy'%self.year)
261 if self.month: l.append('%sm'%self.month)
262 if self.day: l.append('%sd'%self.day)
263 if self.second:
264 l.append('%d:%02d:%02d'%(self.hour, self.minute, self.second))
265 elif self.hour or self.minute:
266 l.append('%d:%02d'%(self.hour, self.minute))
267 return ' '.join(l)
269 def set(self, spec, interval_re = re.compile('''
270 \s*
271 (?P<s>[-+])? # + or -
272 \s*
273 ((?P<y>\d+\s*)y)? # year
274 \s*
275 ((?P<m>\d+\s*)m)? # month
276 \s*
277 ((?P<w>\d+\s*)w)? # week
278 \s*
279 ((?P<d>\d+\s*)d)? # day
280 \s*
281 (((?P<H>\d?\d):(?P<M>\d\d))?(:(?P<S>\d\d))?)? # time
282 \s*
283 ''', re.VERBOSE)):
284 ''' set the date to the value in spec
285 '''
286 self.year = self.month = self.week = self.day = self.hour = \
287 self.minute = self.second = 0
288 self.sign = 1
289 m = interval_re.match(spec)
290 if not m:
291 raise ValueError, 'Not an interval spec: [+-] [#y] [#m] [#w] [#d] [[[H]H:MM]:SS]'
293 info = m.groupdict()
294 for group, attr in {'y':'year', 'm':'month', 'w':'week', 'd':'day',
295 'H':'hour', 'M':'minute', 'S':'second'}.items():
296 if info[group] is not None:
297 setattr(self, attr, int(info[group]))
299 if self.week:
300 self.day = self.day + self.week*7
302 if info['s'] is not None:
303 self.sign = {'+':1, '-':-1}[info['s']]
305 def __repr__(self):
306 return '<Interval %s>'%self.__str__()
308 def pretty(self, threshold=('d', 5)):
309 ''' print up the date date using one of these nice formats..
310 < 1 minute
311 < 15 minutes
312 < 30 minutes
313 < 1 hour
314 < 12 hours
315 < 1 day
316 otherwise, return None (so a full date may be displayed)
317 '''
318 if self.year or self.month > 2:
319 return None
320 if self.month or self.day > 13:
321 days = (self.month * 30) + self.day
322 if days > 28:
323 if int(days/30) > 1:
324 return '%s months'%int(days/30)
325 else:
326 return '1 month'
327 else:
328 return '%s weeks'%int(days/7)
329 if self.day > 7:
330 return '1 week'
331 if self.day > 1:
332 return '%s days'%self.day
333 if self.day == 1 or self.hour > 12:
334 return 'yesterday'
335 if self.hour > 1:
336 return '%s hours'%self.hour
337 if self.hour == 1:
338 if self.minute < 15:
339 return 'an hour'
340 quart = self.minute/15
341 if quart == 2:
342 return '1 1/2 hours'
343 return '1 %s/4 hours'%quart
344 if self.minute < 1:
345 return 'just now'
346 if self.minute == 1:
347 return '1 minute'
348 if self.minute < 15:
349 return '%s minutes'%self.minute
350 quart = int(self.minute/15)
351 if quart == 2:
352 return '1/2 an hour'
353 return '%s/4 hour'%quart
355 def get_tuple(self):
356 return (self.year, self.month, self.day, self.hour, self.minute,
357 self.second)
360 def test():
361 intervals = (" 3w 1 d 2:00", " + 2d", "3w")
362 for interval in intervals:
363 print '>>> Interval("%s")'%interval
364 print `Interval(interval)`
366 dates = (".", "2000-06-25.19:34:02", ". + 2d", "1997-04-17", "01-25",
367 "08-13.22:13", "14:25")
368 for date in dates:
369 print '>>> Date("%s")'%date
370 print `Date(date)`
372 sums = ((". + 2d", "3w"), (".", " 3w 1 d 2:00"))
373 for date, interval in sums:
374 print '>>> Date("%s") + Interval("%s")'%(date, interval)
375 print `Date(date) + Interval(interval)`
377 if __name__ == '__main__':
378 test()
380 #
381 # $Log: not supported by cvs2svn $
382 # Revision 1.12 2001/08/17 03:08:11 richard
383 # fixed prettification of intervals of 1 week
384 #
385 # Revision 1.11 2001/08/15 23:43:18 richard
386 # Fixed some isFooTypes that I missed.
387 # Refactored some code in the CGI code.
388 #
389 # Revision 1.10 2001/08/07 00:24:42 richard
390 # stupid typo
391 #
392 # Revision 1.9 2001/08/07 00:15:51 richard
393 # Added the copyright/license notice to (nearly) all files at request of
394 # Bizar Software.
395 #
396 # Revision 1.8 2001/08/05 07:46:12 richard
397 # Changed date.Date to use regular string formatting instead of strftime -
398 # win32 seems to have problems with %T and no hour... or something...
399 #
400 # Revision 1.7 2001/08/02 00:27:04 richard
401 # Extended the range of intervals that are pretty-printed before actual dates
402 # are displayed.
403 #
404 # Revision 1.6 2001/07/31 09:54:18 richard
405 # Fixed the 2.1-specific gmtime() (no arg) call in roundup.date. (Paul Wright)
406 #
407 # Revision 1.5 2001/07/29 07:01:39 richard
408 # Added vim command to all source so that we don't get no steenkin' tabs :)
409 #
410 # Revision 1.4 2001/07/25 04:09:34 richard
411 # Fixed offset handling (shoulda read the spec a little better)
412 #
413 # Revision 1.3 2001/07/23 07:56:05 richard
414 # Storing only marshallable data in the db - no nasty pickled class references.
415 #
416 # Revision 1.2 2001/07/22 12:09:32 richard
417 # Final commit of Grande Splite
418 #
419 # Revision 1.1 2001/07/22 11:58:35 richard
420 # More Grande Splite
421 #
422 #
423 # vim: set filetype=python ts=4 sw=4 et si