blob: 7f55d24df518c87cd11a5ceb9081697390a486ff [file] [log] [blame]
Guido van Rossum102abab1993-10-30 12:38:16 +00001# Class Date supplies date objects that support date arithmetic.
2#
3# Date(month,day,year) returns a Date object. An instance prints as,
4# e.g., 'Mon 16 Aug 1993'.
5#
6# Addition, subtraction, comparison operators, min, max, and sorting
7# all work as expected for date objects: int+date or date+int returns
8# the date `int' days from `date'; date+date raises an exception;
9# date-int returns the date `int' days before `date'; date2-date1 returns
10# an integer, the number of days from date1 to date2; int-date raises an
11# exception; date1 < date2 is true iff date1 occurs before date2 (&
12# similarly for other comparisons); min(date1,date2) is the earlier of
13# the two dates and max(date1,date2) the later; and date objects can be
14# used as dictionary keys.
15#
16# Date objects support one visible method, date.weekday(). This returns
17# the day of the week the date falls on, as a string.
18#
Guido van Rossum2e611031994-10-09 22:36:28 +000019# Date objects also have 4 read-only data attributes:
Guido van Rossum102abab1993-10-30 12:38:16 +000020# .month in 1..12
21# .day in 1..31
22# .year int or long int
23# .ord the ordinal of the date relative to an arbitrary staring point
24#
25# The Dates module also supplies function today(), which returns the
26# current date as a date object.
27#
28# Those entranced by calendar trivia will be disappointed, as no attempt
29# has been made to accommodate the Julian (etc) system. On the other
30# hand, at least this package knows that 2000 is a leap year but 2100
31# isn't, and works fine for years with a hundred decimal digits <wink>.
32
33# Tim Peters tim@ksr.com
34# not speaking for Kendall Square Research Corp
35
Guido van Rossum2e611031994-10-09 22:36:28 +000036# Adapted to Python 1.1 (where some hacks to overcome coercion are unnecessary)
37# by Guido van Rossum
38
39# vi:set tabsize=8:
40
Guido van Rossum102abab1993-10-30 12:38:16 +000041_MONTH_NAMES = [ 'January', 'February', 'March', 'April', 'May',
42 'June', 'July', 'August', 'September', 'October',
43 'November', 'December' ]
44
45_DAY_NAMES = [ 'Friday', 'Saturday', 'Sunday', 'Monday',
46 'Tuesday', 'Wednesday', 'Thursday' ]
47
48_DAYS_IN_MONTH = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ]
49
50_DAYS_BEFORE_MONTH = []
51dbm = 0
52for dim in _DAYS_IN_MONTH:
53 _DAYS_BEFORE_MONTH.append(dbm)
54 dbm = dbm + dim
55del dbm, dim
56
57_INT_TYPES = type(1), type(1L)
58
59def _is_leap( year ): # 1 if leap year, else 0
60 if year % 4 != 0: return 0
61 if year % 400 == 0: return 1
62 return year % 100 != 0
63
64def _days_in_year( year ): # number of days in year
65 return 365 + _is_leap(year)
66
67def _days_before_year( year ): # number of days before year
68 return year*365L + (year+3)/4 - (year+99)/100 + (year+399)/400
69
70def _days_in_month( month, year ): # number of days in month of year
71 if month == 2 and _is_leap(year): return 29
72 return _DAYS_IN_MONTH[month-1]
73
74def _days_before_month( month, year ): # number of days in year before month
75 return _DAYS_BEFORE_MONTH[month-1] + (month > 2 and _is_leap(year))
76
77def _date2num( date ): # compute ordinal of date.month,day,year
78 return _days_before_year( date.year ) + \
79 _days_before_month( date.month, date.year ) + \
80 date.day
81
82_DI400Y = _days_before_year( 400 ) # number of days in 400 years
83
84def _num2date( n ): # return date with ordinal n
85 if type(n) not in _INT_TYPES:
86 raise TypeError, 'argument must be integer: ' + `type(n)`
87
88 ans = Date(1,1,1) # arguments irrelevant; just getting a Date obj
Guido van Rossum2e611031994-10-09 22:36:28 +000089 del ans.ord, ans.month, ans.day, ans.year # un-initialize it
Guido van Rossum102abab1993-10-30 12:38:16 +000090 ans.ord = n
91
92 n400 = (n-1)/_DI400Y # # of 400-year blocks preceding
93 year, n = 400 * n400, n - _DI400Y * n400
94 more = n / 365
95 dby = _days_before_year( more )
96 if dby >= n:
97 more = more - 1
98 dby = dby - _days_in_year( more )
99 year, n = year + more, int(n - dby)
100
101 try: year = int(year) # chop to int, if it fits
Guido van Rossum2e611031994-10-09 22:36:28 +0000102 except (ValueError, OverflowError): pass
Guido van Rossum102abab1993-10-30 12:38:16 +0000103
104 month = min( n/29 + 1, 12 )
105 dbm = _days_before_month( month, year )
106 if dbm >= n:
107 month = month - 1
108 dbm = dbm - _days_in_month( month, year )
109
110 ans.month, ans.day, ans.year = month, n-dbm, year
111 return ans
112
113def _num2day( n ): # return weekday name of day with ordinal n
114 return _DAY_NAMES[ int(n % 7) ]
115
116
117class Date:
118 def __init__( self, month, day, year ):
119 if not 1 <= month <= 12:
120 raise ValueError, 'month must be in 1..12: ' + `month`
121 dim = _days_in_month( month, year )
122 if not 1 <= day <= dim:
123 raise ValueError, 'day must be in 1..' + `dim` + ': ' + `day`
124 self.month, self.day, self.year = month, day, year
125 self.ord = _date2num( self )
126
Guido van Rossum2e611031994-10-09 22:36:28 +0000127 # don't allow setting existing attributes
128 def __setattr__( self, name, value ):
129 if self.__dict__.has_key(name):
130 raise AttributeError, 'read-only attribute ' + name
131 self.__dict__[name] = value
132
Guido van Rossum102abab1993-10-30 12:38:16 +0000133 def __cmp__( self, other ):
134 return cmp( self.ord, other.ord )
135
136 # define a hash function so dates can be used as dictionary keys
137 def __hash__( self ):
138 return hash( self.ord )
139
140 # print as, e.g., Mon 16 Aug 1993
141 def __repr__( self ):
142 return '%.3s %2d %.3s ' % (
143 self.weekday(),
144 self.day,
145 _MONTH_NAMES[self.month-1] ) + `self.year`
146
Guido van Rossum2e611031994-10-09 22:36:28 +0000147 # Python 1.1 coerces neither int+date nor date+int
Guido van Rossum102abab1993-10-30 12:38:16 +0000148 def __add__( self, n ):
149 if type(n) not in _INT_TYPES:
150 raise TypeError, 'can\'t add ' + `type(n)` + ' to date'
151 return _num2date( self.ord + n )
Guido van Rossum2e611031994-10-09 22:36:28 +0000152 __radd__ = __add__ # handle int+date
Guido van Rossum102abab1993-10-30 12:38:16 +0000153
Guido van Rossum2e611031994-10-09 22:36:28 +0000154 # Python 1.1 coerces neither date-int nor date-date
Guido van Rossum102abab1993-10-30 12:38:16 +0000155 def __sub__( self, other ):
Guido van Rossum2e611031994-10-09 22:36:28 +0000156 if type(other) in _INT_TYPES: # date-int
157 return _num2date( self.ord - other )
Guido van Rossum102abab1993-10-30 12:38:16 +0000158 else:
159 return self.ord - other.ord # date-date
160
Guido van Rossum2e611031994-10-09 22:36:28 +0000161 # complain about int-date
162 def __rsub__( self, other ):
163 raise TypeError, 'Can\'t subtract date from integer'
164
Guido van Rossum102abab1993-10-30 12:38:16 +0000165 def weekday( self ):
166 return _num2day( self.ord )
167
Guido van Rossum102abab1993-10-30 12:38:16 +0000168def today():
169 import time
170 local = time.localtime(time.time())
171 return Date( local[1], local[2], local[0] )
172
173DateTestError = 'DateTestError'
174def test( firstyear, lastyear ):
175 a = Date(9,30,1913)
176 b = Date(9,30,1914)
177 if `a` != 'Tue 30 Sep 1913':
178 raise DateTestError, '__repr__ failure'
Guido van Rossum2e611031994-10-09 22:36:28 +0000179 if (not a < b) or a == b or a > b or b != b:
Guido van Rossum102abab1993-10-30 12:38:16 +0000180 raise DateTestError, '__cmp__ failure'
181 if a+365 != b or 365+a != b:
182 raise DateTestError, '__add__ failure'
183 if b-a != 365 or b-365 != a:
184 raise DateTestError, '__sub__ failure'
185 try:
186 x = 1 - a
187 raise DateTestError, 'int-date should have failed'
188 except TypeError:
189 pass
190 try:
191 x = a + b
192 raise DateTestError, 'date+date should have failed'
193 except TypeError:
194 pass
195 if a.weekday() != 'Tuesday':
196 raise DateTestError, 'weekday() failure'
197 if max(a,b) is not b or min(a,b) is not a:
198 raise DateTestError, 'min/max failure'
199 d = {a-1:b, b:a+1}
200 if d[b-366] != b or d[a+(b-a)] != Date(10,1,1913):
201 raise DateTestError, 'dictionary failure'
202
203 # verify date<->number conversions for first and last days for
204 # all years in firstyear .. lastyear
205
206 lord = _days_before_year( firstyear )
207 y = firstyear
208 while y <= lastyear:
209 ford = lord + 1
210 lord = ford + _days_in_year(y) - 1
211 fd, ld = Date(1,1,y), Date(12,31,y)
212 if (fd.ord,ld.ord) != (ford,lord):
213 raise DateTestError, ('date->num failed', y)
214 fd, ld = _num2date(ford), _num2date(lord)
215 if (1,1,y,12,31,y) != \
216 (fd.month,fd.day,fd.year,ld.month,ld.day,ld.year):
217 raise DateTestError, ('num->date failed', y)
218 y = y + 1