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