1 # $Id: date.py,v 1.3 2001-07-23 07:56:05 richard Exp $
3 import time, re, calendar
5 class Date:
6 '''
7 As strings, date-and-time stamps are specified with the date in
8 international standard format (yyyy-mm-dd) joined to the time
9 (hh:mm:ss) by a period ("."). Dates in this form can be easily compared
10 and are fairly readable when printed. An example of a valid stamp is
11 "2000-06-24.13:03:59". We'll call this the "full date format". When
12 Timestamp objects are printed as strings, they appear in the full date
13 format with the time always given in GMT. The full date format is
14 always exactly 19 characters long.
16 For user input, some partial forms are also permitted: the whole time
17 or just the seconds may be omitted; and the whole date may be omitted
18 or just the year may be omitted. If the time is given, the time is
19 interpreted in the user's local time zone. The Date constructor takes
20 care of these conversions. In the following examples, suppose that yyyy
21 is the current year, mm is the current month, and dd is the current day
22 of the month; and suppose that the user is on Eastern Standard Time.
24 "2000-04-17" means <Date 2000-04-17.00:00:00>
25 "01-25" means <Date yyyy-01-25.00:00:00>
26 "2000-04-17.03:45" means <Date 2000-04-17.08:45:00>
27 "08-13.22:13" means <Date yyyy-08-14.03:13:00>
28 "11-07.09:32:43" means <Date yyyy-11-07.14:32:43>
29 "14:25" means <Date yyyy-mm-dd.19:25:00>
30 "8:47:11" means <Date yyyy-mm-dd.13:47:11>
31 "." means "right now"
33 The Date class should understand simple date expressions of the form
34 stamp + interval and stamp - interval. When adding or subtracting
35 intervals involving months or years, the components are handled
36 separately. For example, when evaluating "2000-06-25 + 1m 10d", we
37 first add one month to get 2000-07-25, then add 10 days to get
38 2000-08-04 (rather than trying to decide whether 1m 10d means 38 or 40
39 or 41 days).
41 Example usage:
42 >>> Date(".")
43 <Date 2000-06-26.00:34:02>
44 >>> _.local(-5)
45 "2000-06-25.19:34:02"
46 >>> Date(". + 2d")
47 <Date 2000-06-28.00:34:02>
48 >>> Date("1997-04-17", -5)
49 <Date 1997-04-17.00:00:00>
50 >>> Date("01-25", -5)
51 <Date 2000-01-25.00:00:00>
52 >>> Date("08-13.22:13", -5)
53 <Date 2000-08-14.03:13:00>
54 >>> Date("14:25", -5)
55 <Date 2000-06-25.19:25:00>
56 '''
57 isDate = 1
59 def __init__(self, spec='.', offset=0):
60 """Construct a date given a specification and a time zone offset.
62 'spec' is a full date or a partial form, with an optional
63 added or subtracted interval. Or a date 9-tuple.
64 'offset' is the local time zone offset from GMT in hours.
65 """
66 if type(spec) == type(''):
67 self.set(spec, offset=offset)
68 else:
69 self.year, self.month, self.day, self.hour, self.minute, \
70 self.second, x, x, x = spec
71 self.offset = offset
73 def applyInterval(self, interval):
74 ''' Apply the interval to this date
75 '''
76 t = (self.year + interval.year,
77 self.month + interval.month,
78 self.day + interval.day,
79 self.hour + interval.hour,
80 self.minute + interval.minute,
81 self.second + interval.second, 0, 0, 0)
82 self.year, self.month, self.day, self.hour, self.minute, \
83 self.second, x, x, x = time.gmtime(calendar.timegm(t))
85 def __add__(self, other):
86 """Add an interval to this date to produce another date."""
87 t = (self.year + other.sign * other.year,
88 self.month + other.sign * other.month,
89 self.day + other.sign * other.day,
90 self.hour + other.sign * other.hour,
91 self.minute + other.sign * other.minute,
92 self.second + other.sign * other.second, 0, 0, 0)
93 return Date(time.gmtime(calendar.timegm(t)))
95 # XXX deviates from spec to allow subtraction of dates as well
96 def __sub__(self, other):
97 """ Subtract:
98 1. an interval from this date to produce another date.
99 2. a date from this date to produce an interval.
100 """
101 if other.isDate:
102 # TODO this code will fall over laughing if the dates cross
103 # leap years, phases of the moon, ....
104 a = calendar.timegm((self.year, self.month, self.day, self.hour,
105 self.minute, self.second, 0, 0, 0))
106 b = calendar.timegm((other.year, other.month, other.day, other.hour,
107 other.minute, other.second, 0, 0, 0))
108 diff = a - b
109 if diff < 0:
110 sign = -1
111 diff = -diff
112 else:
113 sign = 1
114 S = diff%60
115 M = (diff/60)%60
116 H = (diff/(60*60))%60
117 if H>1: S = 0
118 d = (diff/(24*60*60))%30
119 if d>1: H = S = M = 0
120 m = (diff/(30*24*60*60))%12
121 if m>1: H = S = M = 0
122 y = (diff/(365*24*60*60))
123 if y>1: d = H = S = M = 0
124 return Interval((y, m, d, H, M, S), sign=sign)
125 t = (self.year - other.sign * other.year,
126 self.month - other.sign * other.month,
127 self.day - other.sign * other.day,
128 self.hour - other.sign * other.hour,
129 self.minute - other.sign * other.minute,
130 self.second - other.sign * other.second, 0, 0, 0)
131 return Date(time.gmtime(calendar.timegm(t)))
133 def __cmp__(self, other):
134 """Compare this date to another date."""
135 for attr in ('year', 'month', 'day', 'hour', 'minute', 'second'):
136 r = cmp(getattr(self, attr), getattr(other, attr))
137 if r: return r
138 return 0
140 def __str__(self):
141 """Return this date as a string in the yyyy-mm-dd.hh:mm:ss format."""
142 return time.strftime('%Y-%m-%d.%T', (self.year, self.month,
143 self.day, self.hour, self.minute, self.second, 0, 0, 0))
145 def pretty(self):
146 ''' print up the date date using a pretty format...
147 '''
148 return time.strftime('%e %B %Y', (self.year, self.month,
149 self.day, self.hour, self.minute, self.second, 0, 0, 0))
151 def set(self, spec, offset=0, date_re=re.compile(r'''
152 (((?P<y>\d\d\d\d)-)?((?P<m>\d\d)-(?P<d>\d\d))?)? # yyyy-mm-dd
153 (?P<n>\.)? # .
154 (((?P<H>\d?\d):(?P<M>\d\d))?(:(?P<S>\d\d))?)? # hh:mm:ss
155 (?P<o>.+)? # offset
156 ''', re.VERBOSE)):
157 ''' set the date to the value in spec
158 '''
159 m = date_re.match(spec)
160 if not m:
161 raise ValueError, 'Not a date spec: [[yyyy-]mm-dd].[[h]h:mm[:ss]] [offset]'
162 info = m.groupdict()
164 # get the current date/time using the offset
165 y,m,d,H,M,S,x,x,x = time.gmtime(time.time())
166 ts = calendar.timegm((y,m,d,H+offset,M,S,0,0,0))
167 self.year, self.month, self.day, self.hour, self.minute, \
168 self.second, x, x, x = time.gmtime(ts)
170 if info['m'] is not None and info['d'] is not None:
171 self.month = int(info['m'])
172 self.day = int(info['d'])
173 if info['y'] is not None:
174 self.year = int(info['y'])
175 self.hour = self.minute = self.second = 0
177 if info['H'] is not None and info['M'] is not None:
178 self.hour = int(info['H'])
179 self.minute = int(info['M'])
180 if info['S'] is not None:
181 self.second = int(info['S'])
183 if info['o']:
184 self.applyInterval(Interval(info['o']))
186 def __repr__(self):
187 return '<Date %s>'%self.__str__()
189 def local(self, offset):
190 """Return this date as yyyy-mm-dd.hh:mm:ss in a local time zone."""
191 t = (self.year, self.month, self.day, self.hour + offset, self.minute,
192 self.second, 0, 0, 0)
193 self.year, self.month, self.day, self.hour, self.minute, \
194 self.second, x, x, x = time.gmtime(calendar.timegm(t))
196 def get_tuple(self):
197 return (self.year, self.month, self.day, self.hour, self.minute,
198 self.second, 0, 0, 0)
200 class Interval:
201 '''
202 Date intervals are specified using the suffixes "y", "m", and "d". The
203 suffix "w" (for "week") means 7 days. Time intervals are specified in
204 hh:mm:ss format (the seconds may be omitted, but the hours and minutes
205 may not).
207 "3y" means three years
208 "2y 1m" means two years and one month
209 "1m 25d" means one month and 25 days
210 "2w 3d" means two weeks and three days
211 "1d 2:50" means one day, two hours, and 50 minutes
212 "14:00" means 14 hours
213 "0:04:33" means four minutes and 33 seconds
215 Example usage:
216 >>> Interval(" 3w 1 d 2:00")
217 <Interval 22d 2:00>
218 >>> Date(". + 2d") - Interval("3w")
219 <Date 2000-06-07.00:34:02>
220 '''
221 isInterval = 1
223 def __init__(self, spec, sign=1):
224 """Construct an interval given a specification."""
225 if type(spec) == type(''):
226 self.set(spec)
227 else:
228 self.sign = sign
229 self.year, self.month, self.day, self.hour, self.minute, \
230 self.second = spec
232 def __cmp__(self, other):
233 """Compare this interval to another interval."""
234 for attr in ('year', 'month', 'day', 'hour', 'minute', 'second'):
235 r = cmp(getattr(self, attr), getattr(other, attr))
236 if r: return r
237 return 0
239 def __str__(self):
240 """Return this interval as a string."""
241 sign = {1:'+', -1:'-'}[self.sign]
242 l = [sign]
243 if self.year: l.append('%sy'%self.year)
244 if self.month: l.append('%sm'%self.month)
245 if self.day: l.append('%sd'%self.day)
246 if self.second:
247 l.append('%d:%02d:%02d'%(self.hour, self.minute, self.second))
248 elif self.hour or self.minute:
249 l.append('%d:%02d'%(self.hour, self.minute))
250 return ' '.join(l)
252 def set(self, spec, interval_re = re.compile('''
253 \s*
254 (?P<s>[-+])? # + or -
255 \s*
256 ((?P<y>\d+\s*)y)? # year
257 \s*
258 ((?P<m>\d+\s*)m)? # month
259 \s*
260 ((?P<w>\d+\s*)w)? # week
261 \s*
262 ((?P<d>\d+\s*)d)? # day
263 \s*
264 (((?P<H>\d?\d):(?P<M>\d\d))?(:(?P<S>\d\d))?)? # time
265 \s*
266 ''', re.VERBOSE)):
267 ''' set the date to the value in spec
268 '''
269 self.year = self.month = self.week = self.day = self.hour = \
270 self.minute = self.second = 0
271 self.sign = 1
272 m = interval_re.match(spec)
273 if not m:
274 raise ValueError, 'Not an interval spec: [+-] [#y] [#m] [#w] [#d] [[[H]H:MM]:SS]'
276 info = m.groupdict()
277 for group, attr in {'y':'year', 'm':'month', 'w':'week', 'd':'day',
278 'H':'hour', 'M':'minute', 'S':'second'}.items():
279 if info[group] is not None:
280 setattr(self, attr, int(info[group]))
282 if self.week:
283 self.day = self.day + self.week*7
285 if info['s'] is not None:
286 self.sign = {'+':1, '-':-1}[info['s']]
288 def __repr__(self):
289 return '<Interval %s>'%self.__str__()
291 def pretty(self, threshold=('d', 5)):
292 ''' print up the date date using one of these nice formats..
293 < 1 minute
294 < 15 minutes
295 < 30 minutes
296 < 1 hour
297 < 12 hours
298 < 1 day
299 otherwise, return None (so a full date may be displayed)
300 '''
301 if self.year or self.month or self.day > 5:
302 return None
303 if self.day > 1:
304 return '%s days'%self.day
305 if self.day == 1 or self.hour > 12:
306 return 'yesterday'
307 if self.hour > 1:
308 return '%s hours'%self.hour
309 if self.hour == 1:
310 if self.minute < 15:
311 return 'an hour'
312 quart = self.minute/15
313 if quart == 2:
314 return '1 1/2 hours'
315 return '1 %s/4 hours'%quart
316 if self.minute < 1:
317 return 'just now'
318 if self.minute == 1:
319 return '1 minute'
320 if self.minute < 15:
321 return '%s minutes'%self.minute
322 quart = self.minute/15
323 if quart == 2:
324 return '1/2 an hour'
325 return '%s/4 hour'%quart
327 def get_tuple(self):
328 return (self.year, self.month, self.day, self.hour, self.minute,
329 self.second)
332 def test():
333 intervals = (" 3w 1 d 2:00", " + 2d", "3w")
334 for interval in intervals:
335 print '>>> Interval("%s")'%interval
336 print `Interval(interval)`
338 dates = (".", "2000-06-25.19:34:02", ". + 2d", "1997-04-17", "01-25",
339 "08-13.22:13", "14:25")
340 for date in dates:
341 print '>>> Date("%s")'%date
342 print `Date(date)`
344 sums = ((". + 2d", "3w"), (".", " 3w 1 d 2:00"))
345 for date, interval in sums:
346 print '>>> Date("%s") + Interval("%s")'%(date, interval)
347 print `Date(date) + Interval(interval)`
349 if __name__ == '__main__':
350 test()
352 #
353 # $Log: not supported by cvs2svn $
354 # Revision 1.2 2001/07/22 12:09:32 richard
355 # Final commit of Grande Splite
356 #
357 # Revision 1.1 2001/07/22 11:58:35 richard
358 # More Grande Splite
359 #