e516de2db95c43c8691611dcbd3094e5e0bad728
1 # $Id: date.py,v 1.1 2001-07-22 11:58:35 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, set=None):
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.
64 'offset' is the local time zone offset from GMT in hours.
65 """
66 if set is None:
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 = set
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(set = 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(set = 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))
197 class Interval:
198 '''
199 Date intervals are specified using the suffixes "y", "m", and "d". The
200 suffix "w" (for "week") means 7 days. Time intervals are specified in
201 hh:mm:ss format (the seconds may be omitted, but the hours and minutes
202 may not).
204 "3y" means three years
205 "2y 1m" means two years and one month
206 "1m 25d" means one month and 25 days
207 "2w 3d" means two weeks and three days
208 "1d 2:50" means one day, two hours, and 50 minutes
209 "14:00" means 14 hours
210 "0:04:33" means four minutes and 33 seconds
212 Example usage:
213 >>> Interval(" 3w 1 d 2:00")
214 <Interval 22d 2:00>
215 >>> Date(". + 2d") - Interval("3w")
216 <Date 2000-06-07.00:34:02>
217 '''
218 isInterval = 1
220 def __init__(self, spec, sign=1):
221 """Construct an interval given a specification."""
222 if type(spec) == type(''):
223 self.set(spec)
224 else:
225 self.sign = sign
226 self.year, self.month, self.day, self.hour, self.minute, \
227 self.second = spec
229 def __cmp__(self, other):
230 """Compare this interval to another interval."""
231 for attr in ('year', 'month', 'day', 'hour', 'minute', 'second'):
232 r = cmp(getattr(self, attr), getattr(other, attr))
233 if r: return r
234 return 0
236 def __str__(self):
237 """Return this interval as a string."""
238 sign = {1:'+', -1:'-'}[self.sign]
239 l = [sign]
240 if self.year: l.append('%sy'%self.year)
241 if self.month: l.append('%sm'%self.month)
242 if self.day: l.append('%sd'%self.day)
243 if self.second:
244 l.append('%d:%02d:%02d'%(self.hour, self.minute, self.second))
245 elif self.hour or self.minute:
246 l.append('%d:%02d'%(self.hour, self.minute))
247 return ' '.join(l)
249 def set(self, spec, interval_re = re.compile('''
250 \s*
251 (?P<s>[-+])? # + or -
252 \s*
253 ((?P<y>\d+\s*)y)? # year
254 \s*
255 ((?P<m>\d+\s*)m)? # month
256 \s*
257 ((?P<w>\d+\s*)w)? # week
258 \s*
259 ((?P<d>\d+\s*)d)? # day
260 \s*
261 (((?P<H>\d?\d):(?P<M>\d\d))?(:(?P<S>\d\d))?)? # time
262 \s*
263 ''', re.VERBOSE)):
264 ''' set the date to the value in spec
265 '''
266 self.year = self.month = self.week = self.day = self.hour = \
267 self.minute = self.second = 0
268 self.sign = 1
269 m = interval_re.match(spec)
270 if not m:
271 raise ValueError, 'Not an interval spec: [+-] [#y] [#m] [#w] [#d] [[[H]H:MM]:SS]'
273 info = m.groupdict()
274 for group, attr in {'y':'year', 'm':'month', 'w':'week', 'd':'day',
275 'H':'hour', 'M':'minute', 'S':'second'}.items():
276 if info[group] is not None:
277 setattr(self, attr, int(info[group]))
279 if self.week:
280 self.day = self.day + self.week*7
282 if info['s'] is not None:
283 self.sign = {'+':1, '-':-1}[info['s']]
285 def __repr__(self):
286 return '<Interval %s>'%self.__str__()
288 def pretty(self, threshold=('d', 5)):
289 ''' print up the date date using one of these nice formats..
290 < 1 minute
291 < 15 minutes
292 < 30 minutes
293 < 1 hour
294 < 12 hours
295 < 1 day
296 otherwise, return None (so a full date may be displayed)
297 '''
298 if self.year or self.month or self.day > 5:
299 return None
300 if self.day > 1:
301 return '%s days'%self.day
302 if self.day == 1 or self.hour > 12:
303 return 'yesterday'
304 if self.hour > 1:
305 return '%s hours'%self.hour
306 if self.hour == 1:
307 if self.minute < 15:
308 return 'an hour'
309 quart = self.minute/15
310 if quart == 2:
311 return '1 1/2 hours'
312 return '1 %s/4 hours'%quart
313 if self.minute < 1:
314 return 'just now'
315 if self.minute == 1:
316 return '1 minute'
317 if self.minute < 15:
318 return '%s minutes'%self.minute
319 quart = self.minute/15
320 if quart == 2:
321 return '1/2 an hour'
322 return '%s/4 hour'%quart
325 def test():
326 intervals = (" 3w 1 d 2:00", " + 2d", "3w")
327 for interval in intervals:
328 print '>>> Interval("%s")'%interval
329 print `Interval(interval)`
331 dates = (".", "2000-06-25.19:34:02", ". + 2d", "1997-04-17", "01-25",
332 "08-13.22:13", "14:25")
333 for date in dates:
334 print '>>> Date("%s")'%date
335 print `Date(date)`
337 sums = ((". + 2d", "3w"), (".", " 3w 1 d 2:00"))
338 for date, interval in sums:
339 print '>>> Date("%s") + Interval("%s")'%(date, interval)
340 print `Date(date) + Interval(interval)`
342 if __name__ == '__main__':
343 test()
345 #
346 # $Log: not supported by cvs2svn $
347 # Revision 1.3 2001/07/19 06:27:07 anthonybaxter
348 # fixing (manually) the (dollarsign)Log(dollarsign) entries caused by
349 # my using the magic (dollarsign)Id(dollarsign) and (dollarsign)Log(dollarsign)
350 # strings in a commit message. I'm a twonk.
351 #
352 # Also broke the help string in two.
353 #
354 # Revision 1.2 2001/07/19 05:52:22 anthonybaxter
355 # Added CVS keywords Id and Log to all python files.
356 #
357 #