This commit was manufactured by cvs2svn to create tag 'r221'.
[python/dscho.git] / Lib / calendar.py
blob8c81b5398cb1056511df8fc7242edbf291047588
1 """Calendar printing functions
3 Note when comparing these calendars to the ones printed by cal(1): By
4 default, these calendars have Monday as the first day of the week, and
5 Sunday as the last (the European convention). Use setfirstweekday() to
6 set the first day of the week (0=Monday, 6=Sunday)."""
8 # Revision 2: uses functions from built-in time module
10 # Import functions and variables from time module
11 from time import localtime, mktime, strftime
12 from types import SliceType
14 __all__ = ["error","setfirstweekday","firstweekday","isleap",
15 "leapdays","weekday","monthrange","monthcalendar",
16 "prmonth","month","prcal","calendar","timegm",
17 "month_name", "month_abbr", "day_name", "day_abbr"]
19 # Exception raised for bad input (with string parameter for details)
20 error = ValueError
22 # Constants for months referenced later
23 January = 1
24 February = 2
26 # Number of days per month (except for February in leap years)
27 mdays = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
29 # This module used to have hard-coded lists of day and month names, as
30 # English strings. The classes following emulate a read-only version of
31 # that, but supply localized names. Note that the values are computed
32 # fresh on each call, in case the user changes locale between calls.
34 class _indexer:
35 def __getitem__(self, i):
36 if isinstance(i, SliceType):
37 return self.data[i.start : i.stop]
38 else:
39 # May raise an appropriate exception.
40 return self.data[i]
42 class _localized_month(_indexer):
43 def __init__(self, format):
44 self.format = format
46 def __getitem__(self, i):
47 self.data = [strftime(self.format, (2001, j, 1, 12, 0, 0, 1, 1, 0))
48 for j in range(1, 13)]
49 self.data.insert(0, "")
50 return _indexer.__getitem__(self, i)
52 def __len__(self):
53 return 13
55 class _localized_day(_indexer):
56 def __init__(self, format):
57 self.format = format
59 def __getitem__(self, i):
60 # January 1, 2001, was a Monday.
61 self.data = [strftime(self.format, (2001, 1, j+1, 12, 0, 0, j, j+1, 0))
62 for j in range(7)]
63 return _indexer.__getitem__(self, i)
65 def __len__(self_):
66 return 7
68 # Full and abbreviated names of weekdays
69 day_name = _localized_day('%A')
70 day_abbr = _localized_day('%a')
72 # Full and abbreviated names of months (1-based arrays!!!)
73 month_name = _localized_month('%B')
74 month_abbr = _localized_month('%b')
76 # Constants for weekdays
77 (MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY) = range(7)
79 _firstweekday = 0 # 0 = Monday, 6 = Sunday
81 def firstweekday():
82 return _firstweekday
84 def setfirstweekday(weekday):
85 """Set weekday (Monday=0, Sunday=6) to start each week."""
86 global _firstweekday
87 if not MONDAY <= weekday <= SUNDAY:
88 raise ValueError, \
89 'bad weekday number; must be 0 (Monday) to 6 (Sunday)'
90 _firstweekday = weekday
92 def isleap(year):
93 """Return 1 for leap years, 0 for non-leap years."""
94 return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
96 def leapdays(y1, y2):
97 """Return number of leap years in range [y1, y2).
98 Assume y1 <= y2."""
99 y1 -= 1
100 y2 -= 1
101 return (y2/4 - y1/4) - (y2/100 - y1/100) + (y2/400 - y1/400)
103 def weekday(year, month, day):
104 """Return weekday (0-6 ~ Mon-Sun) for year (1970-...), month (1-12),
105 day (1-31)."""
106 secs = mktime((year, month, day, 0, 0, 0, 0, 0, 0))
107 tuple = localtime(secs)
108 return tuple[6]
110 def monthrange(year, month):
111 """Return weekday (0-6 ~ Mon-Sun) and number of days (28-31) for
112 year, month."""
113 if not 1 <= month <= 12:
114 raise ValueError, 'bad month number'
115 day1 = weekday(year, month, 1)
116 ndays = mdays[month] + (month == February and isleap(year))
117 return day1, ndays
119 def monthcalendar(year, month):
120 """Return a matrix representing a month's calendar.
121 Each row represents a week; days outside this month are zero."""
122 day1, ndays = monthrange(year, month)
123 rows = []
124 r7 = range(7)
125 day = (_firstweekday - day1 + 6) % 7 - 5 # for leading 0's in first week
126 while day <= ndays:
127 row = [0, 0, 0, 0, 0, 0, 0]
128 for i in r7:
129 if 1 <= day <= ndays: row[i] = day
130 day = day + 1
131 rows.append(row)
132 return rows
134 def _center(str, width):
135 """Center a string in a field."""
136 n = width - len(str)
137 if n <= 0:
138 return str
139 return ' '*((n+1)/2) + str + ' '*((n)/2)
141 def prweek(theweek, width):
142 """Print a single week (no newline)."""
143 print week(theweek, width),
145 def week(theweek, width):
146 """Returns a single week in a string (no newline)."""
147 days = []
148 for day in theweek:
149 if day == 0:
150 s = ''
151 else:
152 s = '%2i' % day # right-align single-digit days
153 days.append(_center(s, width))
154 return ' '.join(days)
156 def weekheader(width):
157 """Return a header for a week."""
158 if width >= 9:
159 names = day_name
160 else:
161 names = day_abbr
162 days = []
163 for i in range(_firstweekday, _firstweekday + 7):
164 days.append(_center(names[i%7][:width], width))
165 return ' '.join(days)
167 def prmonth(theyear, themonth, w=0, l=0):
168 """Print a month's calendar."""
169 print month(theyear, themonth, w, l),
171 def month(theyear, themonth, w=0, l=0):
172 """Return a month's calendar string (multi-line)."""
173 w = max(2, w)
174 l = max(1, l)
175 s = (_center(month_name[themonth] + ' ' + `theyear`,
176 7 * (w + 1) - 1).rstrip() +
177 '\n' * l + weekheader(w).rstrip() + '\n' * l)
178 for aweek in monthcalendar(theyear, themonth):
179 s = s + week(aweek, w).rstrip() + '\n' * l
180 return s[:-l] + '\n'
182 # Spacing of month columns for 3-column year calendar
183 _colwidth = 7*3 - 1 # Amount printed by prweek()
184 _spacing = 6 # Number of spaces between columns
186 def format3c(a, b, c, colwidth=_colwidth, spacing=_spacing):
187 """Prints 3-column formatting for year calendars"""
188 print format3cstring(a, b, c, colwidth, spacing)
190 def format3cstring(a, b, c, colwidth=_colwidth, spacing=_spacing):
191 """Returns a string formatted from 3 strings, centered within 3 columns."""
192 return (_center(a, colwidth) + ' ' * spacing + _center(b, colwidth) +
193 ' ' * spacing + _center(c, colwidth))
195 def prcal(year, w=0, l=0, c=_spacing):
196 """Print a year's calendar."""
197 print calendar(year, w, l, c),
199 def calendar(year, w=0, l=0, c=_spacing):
200 """Returns a year's calendar as a multi-line string."""
201 w = max(2, w)
202 l = max(1, l)
203 c = max(2, c)
204 colwidth = (w + 1) * 7 - 1
205 s = _center(`year`, colwidth * 3 + c * 2).rstrip() + '\n' * l
206 header = weekheader(w)
207 header = format3cstring(header, header, header, colwidth, c).rstrip()
208 for q in range(January, January+12, 3):
209 s = (s + '\n' * l +
210 format3cstring(month_name[q], month_name[q+1], month_name[q+2],
211 colwidth, c).rstrip() +
212 '\n' * l + header + '\n' * l)
213 data = []
214 height = 0
215 for amonth in range(q, q + 3):
216 cal = monthcalendar(year, amonth)
217 if len(cal) > height:
218 height = len(cal)
219 data.append(cal)
220 for i in range(height):
221 weeks = []
222 for cal in data:
223 if i >= len(cal):
224 weeks.append('')
225 else:
226 weeks.append(week(cal[i], w))
227 s = s + format3cstring(weeks[0], weeks[1], weeks[2],
228 colwidth, c).rstrip() + '\n' * l
229 return s[:-l] + '\n'
231 EPOCH = 1970
232 def timegm(tuple):
233 """Unrelated but handy function to calculate Unix timestamp from GMT."""
234 year, month, day, hour, minute, second = tuple[:6]
235 assert year >= EPOCH
236 assert 1 <= month <= 12
237 days = 365*(year-EPOCH) + leapdays(EPOCH, year)
238 for i in range(1, month):
239 days = days + mdays[i]
240 if month > 2 and isleap(year):
241 days = days + 1
242 days = days + day - 1
243 hours = days*24 + hour
244 minutes = hours*60 + minute
245 seconds = minutes*60 + second
246 return seconds