This commit was manufactured by cvs2svn to create tag 'r221c1'.
[python/dscho.git] / Lib / calendar.py
blob9af2c933f1abc4b20a976ac3a5a963d256706636
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
13 __all__ = ["error","setfirstweekday","firstweekday","isleap",
14 "leapdays","weekday","monthrange","monthcalendar",
15 "prmonth","month","prcal","calendar","timegm"]
17 # Exception raised for bad input (with string parameter for details)
18 error = ValueError
20 # Constants for months referenced later
21 January = 1
22 February = 2
24 # Number of days per month (except for February in leap years)
25 mdays = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
27 class _localized_name:
28 def __init__(self, format, len):
29 self.format = format
30 self.len = len
31 def __getitem__(self, item):
32 if isinstance(item, int):
33 if item < 0: item += self.len
34 if not 0 <= item < self.len:
35 raise IndexError, "out of range"
36 return strftime(self.format, (item,)*9).capitalize()
37 elif isinstance(item, type(slice(0))):
38 return [self[e] for e in range(self.len)].__getslice__(item.start, item.stop)
39 def __len__(self):
40 return self.len
42 # Full and abbreviated names of weekdays
43 day_name = _localized_name('%A', 7)
44 day_abbr = _localized_name('%a', 7)
46 # Full and abbreviated names of months (1-based arrays!!!)
47 month_name = _localized_name('%B', 13)
48 month_abbr = _localized_name('%b', 13)
50 # Constants for weekdays
51 (MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY) = range(7)
53 _firstweekday = 0 # 0 = Monday, 6 = Sunday
55 def firstweekday():
56 return _firstweekday
58 def setfirstweekday(weekday):
59 """Set weekday (Monday=0, Sunday=6) to start each week."""
60 global _firstweekday
61 if not MONDAY <= weekday <= SUNDAY:
62 raise ValueError, \
63 'bad weekday number; must be 0 (Monday) to 6 (Sunday)'
64 _firstweekday = weekday
66 def isleap(year):
67 """Return 1 for leap years, 0 for non-leap years."""
68 return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
70 def leapdays(y1, y2):
71 """Return number of leap years in range [y1, y2).
72 Assume y1 <= y2."""
73 y1 -= 1
74 y2 -= 1
75 return (y2/4 - y1/4) - (y2/100 - y1/100) + (y2/400 - y1/400)
77 def weekday(year, month, day):
78 """Return weekday (0-6 ~ Mon-Sun) for year (1970-...), month (1-12),
79 day (1-31)."""
80 secs = mktime((year, month, day, 0, 0, 0, 0, 0, 0))
81 tuple = localtime(secs)
82 return tuple[6]
84 def monthrange(year, month):
85 """Return weekday (0-6 ~ Mon-Sun) and number of days (28-31) for
86 year, month."""
87 if not 1 <= month <= 12:
88 raise ValueError, 'bad month number'
89 day1 = weekday(year, month, 1)
90 ndays = mdays[month] + (month == February and isleap(year))
91 return day1, ndays
93 def monthcalendar(year, month):
94 """Return a matrix representing a month's calendar.
95 Each row represents a week; days outside this month are zero."""
96 day1, ndays = monthrange(year, month)
97 rows = []
98 r7 = range(7)
99 day = (_firstweekday - day1 + 6) % 7 - 5 # for leading 0's in first week
100 while day <= ndays:
101 row = [0, 0, 0, 0, 0, 0, 0]
102 for i in r7:
103 if 1 <= day <= ndays: row[i] = day
104 day = day + 1
105 rows.append(row)
106 return rows
108 def _center(str, width):
109 """Center a string in a field."""
110 n = width - len(str)
111 if n <= 0:
112 return str
113 return ' '*((n+1)/2) + str + ' '*((n)/2)
115 def prweek(theweek, width):
116 """Print a single week (no newline)."""
117 print week(theweek, width),
119 def week(theweek, width):
120 """Returns a single week in a string (no newline)."""
121 days = []
122 for day in theweek:
123 if day == 0:
124 s = ''
125 else:
126 s = '%2i' % day # right-align single-digit days
127 days.append(_center(s, width))
128 return ' '.join(days)
130 def weekheader(width):
131 """Return a header for a week."""
132 if width >= 9:
133 names = day_name
134 else:
135 names = day_abbr
136 days = []
137 for i in range(_firstweekday, _firstweekday + 7):
138 days.append(_center(names[i%7][:width], width))
139 return ' '.join(days)
141 def prmonth(theyear, themonth, w=0, l=0):
142 """Print a month's calendar."""
143 print month(theyear, themonth, w, l),
145 def month(theyear, themonth, w=0, l=0):
146 """Return a month's calendar string (multi-line)."""
147 w = max(2, w)
148 l = max(1, l)
149 s = (_center(month_name[themonth] + ' ' + `theyear`,
150 7 * (w + 1) - 1).rstrip() +
151 '\n' * l + weekheader(w).rstrip() + '\n' * l)
152 for aweek in monthcalendar(theyear, themonth):
153 s = s + week(aweek, w).rstrip() + '\n' * l
154 return s[:-l] + '\n'
156 # Spacing of month columns for 3-column year calendar
157 _colwidth = 7*3 - 1 # Amount printed by prweek()
158 _spacing = 6 # Number of spaces between columns
160 def format3c(a, b, c, colwidth=_colwidth, spacing=_spacing):
161 """Prints 3-column formatting for year calendars"""
162 print format3cstring(a, b, c, colwidth, spacing)
164 def format3cstring(a, b, c, colwidth=_colwidth, spacing=_spacing):
165 """Returns a string formatted from 3 strings, centered within 3 columns."""
166 return (_center(a, colwidth) + ' ' * spacing + _center(b, colwidth) +
167 ' ' * spacing + _center(c, colwidth))
169 def prcal(year, w=0, l=0, c=_spacing):
170 """Print a year's calendar."""
171 print calendar(year, w, l, c),
173 def calendar(year, w=0, l=0, c=_spacing):
174 """Returns a year's calendar as a multi-line string."""
175 w = max(2, w)
176 l = max(1, l)
177 c = max(2, c)
178 colwidth = (w + 1) * 7 - 1
179 s = _center(`year`, colwidth * 3 + c * 2).rstrip() + '\n' * l
180 header = weekheader(w)
181 header = format3cstring(header, header, header, colwidth, c).rstrip()
182 for q in range(January, January+12, 3):
183 s = (s + '\n' * l +
184 format3cstring(month_name[q], month_name[q+1], month_name[q+2],
185 colwidth, c).rstrip() +
186 '\n' * l + header + '\n' * l)
187 data = []
188 height = 0
189 for amonth in range(q, q + 3):
190 cal = monthcalendar(year, amonth)
191 if len(cal) > height:
192 height = len(cal)
193 data.append(cal)
194 for i in range(height):
195 weeks = []
196 for cal in data:
197 if i >= len(cal):
198 weeks.append('')
199 else:
200 weeks.append(week(cal[i], w))
201 s = s + format3cstring(weeks[0], weeks[1], weeks[2],
202 colwidth, c).rstrip() + '\n' * l
203 return s[:-l] + '\n'
205 EPOCH = 1970
206 def timegm(tuple):
207 """Unrelated but handy function to calculate Unix timestamp from GMT."""
208 year, month, day, hour, minute, second = tuple[:6]
209 assert year >= EPOCH
210 assert 1 <= month <= 12
211 days = 365*(year-EPOCH) + leapdays(EPOCH, year)
212 for i in range(1, month):
213 days = days + mdays[i]
214 if month > 2 and isleap(year):
215 days = days + 1
216 days = days + day - 1
217 hours = days*24 + hour
218 minutes = hours*60 + minute
219 seconds = minutes*60 + second
220 return seconds