blob: 857bc90a72c2bd2ff1a6107cdeaac090636fc556 [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
Martin v. Löwis7890c262003-06-07 19:39:56 +000039# Note that as of Python 2.3, a datetime module is included in the stardard
40# library.
41
Alexander Belopolskybb3565d2010-07-03 21:42:47 +000042import functools
Guido van Rossum2e611031994-10-09 22:36:28 +000043
Guido van Rossum102abab1993-10-30 12:38:16 +000044_MONTH_NAMES = [ 'January', 'February', 'March', 'April', 'May',
Guido van Rossumdcd038f1998-09-14 15:34:45 +000045 'June', 'July', 'August', 'September', 'October',
46 'November', 'December' ]
Guido van Rossum102abab1993-10-30 12:38:16 +000047
48_DAY_NAMES = [ 'Friday', 'Saturday', 'Sunday', 'Monday',
Guido van Rossumdcd038f1998-09-14 15:34:45 +000049 'Tuesday', 'Wednesday', 'Thursday' ]
Guido van Rossum102abab1993-10-30 12:38:16 +000050
51_DAYS_IN_MONTH = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ]
52
53_DAYS_BEFORE_MONTH = []
54dbm = 0
55for dim in _DAYS_IN_MONTH:
56 _DAYS_BEFORE_MONTH.append(dbm)
57 dbm = dbm + dim
58del dbm, dim
59
Thomas Wouters73e5a5b2006-06-08 15:35:45 +000060def _is_leap(year): # 1 if leap year, else 0
Guido van Rossum102abab1993-10-30 12:38:16 +000061 if year % 4 != 0: return 0
62 if year % 400 == 0: return 1
63 return year % 100 != 0
64
Thomas Wouters73e5a5b2006-06-08 15:35:45 +000065def _days_in_year(year): # number of days in year
Guido van Rossum102abab1993-10-30 12:38:16 +000066 return 365 + _is_leap(year)
67
Thomas Wouters73e5a5b2006-06-08 15:35:45 +000068def _days_before_year(year): # number of days before year
Benjamin Petersond7b03282008-09-13 15:58:53 +000069 return year*365 + (year+3)//4 - (year+99)//100 + (year+399)//400
Guido van Rossum102abab1993-10-30 12:38:16 +000070
Thomas Wouters73e5a5b2006-06-08 15:35:45 +000071def _days_in_month(month, year): # number of days in month of year
Guido van Rossum102abab1993-10-30 12:38:16 +000072 if month == 2 and _is_leap(year): return 29
73 return _DAYS_IN_MONTH[month-1]
74
Thomas Wouters73e5a5b2006-06-08 15:35:45 +000075def _days_before_month(month, year): # number of days in year before month
Guido van Rossum102abab1993-10-30 12:38:16 +000076 return _DAYS_BEFORE_MONTH[month-1] + (month > 2 and _is_leap(year))
77
Thomas Wouters73e5a5b2006-06-08 15:35:45 +000078def _date2num(date): # compute ordinal of date.month,day,year
79 return _days_before_year(date.year) + \
80 _days_before_month(date.month, date.year) + \
Guido van Rossumdcd038f1998-09-14 15:34:45 +000081 date.day
Guido van Rossum102abab1993-10-30 12:38:16 +000082
Thomas Wouters73e5a5b2006-06-08 15:35:45 +000083_DI400Y = _days_before_year(400) # number of days in 400 years
Guido van Rossum102abab1993-10-30 12:38:16 +000084
Thomas Wouters73e5a5b2006-06-08 15:35:45 +000085def _num2date(n): # return date with ordinal n
Alexander Belopolskybb3565d2010-07-03 21:42:47 +000086 if not isinstance(n, int):
Collin Winter6f2df4d2007-07-17 20:59:35 +000087 raise TypeError('argument must be integer: %r' % type(n))
Guido van Rossum102abab1993-10-30 12:38:16 +000088
Guido van Rossumdcd038f1998-09-14 15:34:45 +000089 ans = Date(1,1,1) # arguments irrelevant; just getting a Date obj
Guido van Rossum2e611031994-10-09 22:36:28 +000090 del ans.ord, ans.month, ans.day, ans.year # un-initialize it
Guido van Rossum102abab1993-10-30 12:38:16 +000091 ans.ord = n
92
Benjamin Petersond7b03282008-09-13 15:58:53 +000093 n400 = (n-1)//_DI400Y # # of 400-year blocks preceding
Guido van Rossum102abab1993-10-30 12:38:16 +000094 year, n = 400 * n400, n - _DI400Y * n400
Benjamin Petersond7b03282008-09-13 15:58:53 +000095 more = n // 365
Thomas Wouters73e5a5b2006-06-08 15:35:45 +000096 dby = _days_before_year(more)
Guido van Rossum102abab1993-10-30 12:38:16 +000097 if dby >= n:
Guido van Rossumdcd038f1998-09-14 15:34:45 +000098 more = more - 1
Thomas Wouters73e5a5b2006-06-08 15:35:45 +000099 dby = dby - _days_in_year(more)
Guido van Rossum102abab1993-10-30 12:38:16 +0000100 year, n = year + more, int(n - dby)
101
Guido van Rossumdcd038f1998-09-14 15:34:45 +0000102 try: year = int(year) # chop to int, if it fits
Guido van Rossum2e611031994-10-09 22:36:28 +0000103 except (ValueError, OverflowError): pass
Guido van Rossum102abab1993-10-30 12:38:16 +0000104
Benjamin Petersond7b03282008-09-13 15:58:53 +0000105 month = min(n//29 + 1, 12)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000106 dbm = _days_before_month(month, year)
Guido van Rossum102abab1993-10-30 12:38:16 +0000107 if dbm >= n:
Guido van Rossumdcd038f1998-09-14 15:34:45 +0000108 month = month - 1
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000109 dbm = dbm - _days_in_month(month, year)
Guido van Rossum102abab1993-10-30 12:38:16 +0000110
111 ans.month, ans.day, ans.year = month, n-dbm, year
112 return ans
113
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000114def _num2day(n): # return weekday name of day with ordinal n
Guido van Rossum102abab1993-10-30 12:38:16 +0000115 return _DAY_NAMES[ int(n % 7) ]
116
Alexander Belopolskybb3565d2010-07-03 21:42:47 +0000117@functools.total_ordering
Guido van Rossum102abab1993-10-30 12:38:16 +0000118class Date:
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000119 def __init__(self, month, day, year):
Guido van Rossumdcd038f1998-09-14 15:34:45 +0000120 if not 1 <= month <= 12:
Collin Winter6f2df4d2007-07-17 20:59:35 +0000121 raise ValueError('month must be in 1..12: %r' % (month,))
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000122 dim = _days_in_month(month, year)
Guido van Rossumdcd038f1998-09-14 15:34:45 +0000123 if not 1 <= day <= dim:
Collin Winter6f2df4d2007-07-17 20:59:35 +0000124 raise ValueError('day must be in 1..%r: %r' % (dim, day))
Guido van Rossumdcd038f1998-09-14 15:34:45 +0000125 self.month, self.day, self.year = month, day, year
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000126 self.ord = _date2num(self)
Guido van Rossum102abab1993-10-30 12:38:16 +0000127
Guido van Rossum2e611031994-10-09 22:36:28 +0000128 # don't allow setting existing attributes
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000129 def __setattr__(self, name, value):
Collin Winter6f2df4d2007-07-17 20:59:35 +0000130 if name in self.__dict__:
131 raise AttributeError('read-only attribute ' + name)
Guido van Rossumdcd038f1998-09-14 15:34:45 +0000132 self.__dict__[name] = value
Guido van Rossum2e611031994-10-09 22:36:28 +0000133
Alexander Belopolskybb3565d2010-07-03 21:42:47 +0000134 def __eq__(self, other):
135 return self.ord == other.ord
136
137 def __lt__(self, other):
138 return self.ord < other.ord
Guido van Rossum102abab1993-10-30 12:38:16 +0000139
140 # define a hash function so dates can be used as dictionary keys
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000141 def __hash__(self):
142 return hash(self.ord)
Guido van Rossum102abab1993-10-30 12:38:16 +0000143
144 # print as, e.g., Mon 16 Aug 1993
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000145 def __repr__(self):
Walter Dörwald70a6b492004-02-12 17:35:32 +0000146 return '%.3s %2d %.3s %r' % (
Guido van Rossumdcd038f1998-09-14 15:34:45 +0000147 self.weekday(),
148 self.day,
Walter Dörwald70a6b492004-02-12 17:35:32 +0000149 _MONTH_NAMES[self.month-1],
150 self.year)
Guido van Rossum102abab1993-10-30 12:38:16 +0000151
Guido van Rossum2e611031994-10-09 22:36:28 +0000152 # Python 1.1 coerces neither int+date nor date+int
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000153 def __add__(self, n):
Alexander Belopolskybb3565d2010-07-03 21:42:47 +0000154 if not isinstance(n, int):
Collin Winter6f2df4d2007-07-17 20:59:35 +0000155 raise TypeError('can\'t add %r to date' % type(n))
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000156 return _num2date(self.ord + n)
Guido van Rossum2e611031994-10-09 22:36:28 +0000157 __radd__ = __add__ # handle int+date
Guido van Rossum102abab1993-10-30 12:38:16 +0000158
Guido van Rossum2e611031994-10-09 22:36:28 +0000159 # Python 1.1 coerces neither date-int nor date-date
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000160 def __sub__(self, other):
Alexander Belopolskybb3565d2010-07-03 21:42:47 +0000161 if isinstance(other, int): # date-int
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000162 return _num2date(self.ord - other)
Guido van Rossumdcd038f1998-09-14 15:34:45 +0000163 else:
164 return self.ord - other.ord # date-date
Guido van Rossum102abab1993-10-30 12:38:16 +0000165
Guido van Rossum2e611031994-10-09 22:36:28 +0000166 # complain about int-date
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000167 def __rsub__(self, other):
Collin Winter6f2df4d2007-07-17 20:59:35 +0000168 raise TypeError('Can\'t subtract date from integer')
Guido van Rossum2e611031994-10-09 22:36:28 +0000169
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000170 def weekday(self):
171 return _num2day(self.ord)
Guido van Rossum102abab1993-10-30 12:38:16 +0000172
Guido van Rossum102abab1993-10-30 12:38:16 +0000173def today():
174 import time
175 local = time.localtime(time.time())
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000176 return Date(local[1], local[2], local[0])
Guido van Rossum102abab1993-10-30 12:38:16 +0000177
Benjamin Petersond7b03282008-09-13 15:58:53 +0000178class DateTestError(Exception):
179 pass
180
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000181def test(firstyear, lastyear):
Guido van Rossum102abab1993-10-30 12:38:16 +0000182 a = Date(9,30,1913)
183 b = Date(9,30,1914)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000184 if repr(a) != 'Tue 30 Sep 1913':
Collin Winter6f2df4d2007-07-17 20:59:35 +0000185 raise DateTestError('__repr__ failure')
Guido van Rossum2e611031994-10-09 22:36:28 +0000186 if (not a < b) or a == b or a > b or b != b:
Collin Winter6f2df4d2007-07-17 20:59:35 +0000187 raise DateTestError('__cmp__ failure')
Guido van Rossum102abab1993-10-30 12:38:16 +0000188 if a+365 != b or 365+a != b:
Collin Winter6f2df4d2007-07-17 20:59:35 +0000189 raise DateTestError('__add__ failure')
Guido van Rossum102abab1993-10-30 12:38:16 +0000190 if b-a != 365 or b-365 != a:
Collin Winter6f2df4d2007-07-17 20:59:35 +0000191 raise DateTestError('__sub__ failure')
Guido van Rossum102abab1993-10-30 12:38:16 +0000192 try:
Guido van Rossumdcd038f1998-09-14 15:34:45 +0000193 x = 1 - a
Collin Winter6f2df4d2007-07-17 20:59:35 +0000194 raise DateTestError('int-date should have failed')
Guido van Rossum102abab1993-10-30 12:38:16 +0000195 except TypeError:
Guido van Rossumdcd038f1998-09-14 15:34:45 +0000196 pass
Guido van Rossum102abab1993-10-30 12:38:16 +0000197 try:
Guido van Rossumdcd038f1998-09-14 15:34:45 +0000198 x = a + b
Collin Winter6f2df4d2007-07-17 20:59:35 +0000199 raise DateTestError('date+date should have failed')
Guido van Rossum102abab1993-10-30 12:38:16 +0000200 except TypeError:
Guido van Rossumdcd038f1998-09-14 15:34:45 +0000201 pass
Guido van Rossum102abab1993-10-30 12:38:16 +0000202 if a.weekday() != 'Tuesday':
Collin Winter6f2df4d2007-07-17 20:59:35 +0000203 raise DateTestError('weekday() failure')
Guido van Rossum102abab1993-10-30 12:38:16 +0000204 if max(a,b) is not b or min(a,b) is not a:
Collin Winter6f2df4d2007-07-17 20:59:35 +0000205 raise DateTestError('min/max failure')
Guido van Rossum102abab1993-10-30 12:38:16 +0000206 d = {a-1:b, b:a+1}
207 if d[b-366] != b or d[a+(b-a)] != Date(10,1,1913):
Collin Winter6f2df4d2007-07-17 20:59:35 +0000208 raise DateTestError('dictionary failure')
Guido van Rossum102abab1993-10-30 12:38:16 +0000209
210 # verify date<->number conversions for first and last days for
211 # all years in firstyear .. lastyear
212
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000213 lord = _days_before_year(firstyear)
Guido van Rossum102abab1993-10-30 12:38:16 +0000214 y = firstyear
215 while y <= lastyear:
Guido van Rossumdcd038f1998-09-14 15:34:45 +0000216 ford = lord + 1
217 lord = ford + _days_in_year(y) - 1
218 fd, ld = Date(1,1,y), Date(12,31,y)
219 if (fd.ord,ld.ord) != (ford,lord):
Collin Winter6f2df4d2007-07-17 20:59:35 +0000220 raise DateTestError('date->num failed', y)
Guido van Rossumdcd038f1998-09-14 15:34:45 +0000221 fd, ld = _num2date(ford), _num2date(lord)
222 if (1,1,y,12,31,y) != \
223 (fd.month,fd.day,fd.year,ld.month,ld.day,ld.year):
Collin Winter6f2df4d2007-07-17 20:59:35 +0000224 raise DateTestError('num->date failed', y)
Guido van Rossumdcd038f1998-09-14 15:34:45 +0000225 y = y + 1
Benjamin Petersond7b03282008-09-13 15:58:53 +0000226
227if __name__ == '__main__':
228 test(1850, 2150)