blob: 8c81b5398cb1056511df8fc7242edbf291047588 [file] [log] [blame]
Skip Montanaroad3bc442000-08-30 14:01:28 +00001"""Calendar printing functions
2
3Note when comparing these calendars to the ones printed by cal(1): By
4default, these calendars have Monday as the first day of the week, and
5Sunday as the last (the European convention). Use setfirstweekday() to
6set the first day of the week (0=Monday, 6=Sunday)."""
Guido van Rossumc6360141990-10-13 19:23:40 +00007
Jeremy Hyltona05e2932000-06-28 14:48:01 +00008# Revision 2: uses functions from built-in time module
Guido van Rossumc6360141990-10-13 19:23:40 +00009
Guido van Rossum9b3bc711993-06-20 21:02:22 +000010# Import functions and variables from time module
Barry Warsaw1d099102001-05-22 15:58:30 +000011from time import localtime, mktime, strftime
Tim Peters0c2c8e72002-03-23 03:26:53 +000012from types import SliceType
Guido van Rossumc6360141990-10-13 19:23:40 +000013
Skip Montanaroe99d5ea2001-01-20 19:54:20 +000014__all__ = ["error","setfirstweekday","firstweekday","isleap",
15 "leapdays","weekday","monthrange","monthcalendar",
Tim Peters0c2c8e72002-03-23 03:26:53 +000016 "prmonth","month","prcal","calendar","timegm",
17 "month_name", "month_abbr", "day_name", "day_abbr"]
Skip Montanaroe99d5ea2001-01-20 19:54:20 +000018
Guido van Rossumc6360141990-10-13 19:23:40 +000019# Exception raised for bad input (with string parameter for details)
Guido van Rossum00245cf1999-05-03 18:07:40 +000020error = ValueError
Guido van Rossumc6360141990-10-13 19:23:40 +000021
Guido van Rossum9b3bc711993-06-20 21:02:22 +000022# Constants for months referenced later
23January = 1
24February = 2
25
26# Number of days per month (except for February in leap years)
27mdays = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
28
Tim Peters0c2c8e72002-03-23 03:26:53 +000029# 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.
33
34class _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]
41
42class _localized_month(_indexer):
43 def __init__(self, format):
Barry Warsaw1d099102001-05-22 15:58:30 +000044 self.format = format
Tim Peters0c2c8e72002-03-23 03:26:53 +000045
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)
51
Skip Montanaro4c834952002-03-15 04:08:38 +000052 def __len__(self):
Tim Peters0c2c8e72002-03-23 03:26:53 +000053 return 13
54
55class _localized_day(_indexer):
56 def __init__(self, format):
57 self.format = format
58
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)
64
65 def __len__(self_):
66 return 7
Barry Warsaw1d099102001-05-22 15:58:30 +000067
Guido van Rossum9b3bc711993-06-20 21:02:22 +000068# Full and abbreviated names of weekdays
Tim Peters0c2c8e72002-03-23 03:26:53 +000069day_name = _localized_day('%A')
70day_abbr = _localized_day('%a')
Guido van Rossum9b3bc711993-06-20 21:02:22 +000071
Guido van Rossum5cfa5df1993-06-23 09:30:50 +000072# Full and abbreviated names of months (1-based arrays!!!)
Tim Peters0c2c8e72002-03-23 03:26:53 +000073month_name = _localized_month('%B')
74month_abbr = _localized_month('%b')
Guido van Rossum9b3bc711993-06-20 21:02:22 +000075
Skip Montanaroad3bc442000-08-30 14:01:28 +000076# Constants for weekdays
77(MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY) = range(7)
78
79_firstweekday = 0 # 0 = Monday, 6 = Sunday
80
81def firstweekday():
82 return _firstweekday
83
84def 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
91
Guido van Rossum9b3bc711993-06-20 21:02:22 +000092def isleap(year):
Guido van Rossum4acc25b2000-02-02 15:10:15 +000093 """Return 1 for leap years, 0 for non-leap years."""
Fred Drake8152d322000-12-12 23:20:45 +000094 return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
Guido van Rossum9b3bc711993-06-20 21:02:22 +000095
Guido van Rossum9b3bc711993-06-20 21:02:22 +000096def leapdays(y1, y2):
Guido van Rossum4acc25b2000-02-02 15:10:15 +000097 """Return number of leap years in range [y1, y2).
Guido van Rossum46735ad2000-10-09 12:42:04 +000098 Assume y1 <= y2."""
99 y1 -= 1
100 y2 -= 1
101 return (y2/4 - y1/4) - (y2/100 - y1/100) + (y2/400 - y1/400)
Guido van Rossum9b3bc711993-06-20 21:02:22 +0000102
Guido van Rossumc6360141990-10-13 19:23:40 +0000103def weekday(year, month, day):
Skip Montanaroad3bc442000-08-30 14:01:28 +0000104 """Return weekday (0-6 ~ Mon-Sun) for year (1970-...), month (1-12),
105 day (1-31)."""
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000106 secs = mktime((year, month, day, 0, 0, 0, 0, 0, 0))
107 tuple = localtime(secs)
108 return tuple[6]
Guido van Rossumc6360141990-10-13 19:23:40 +0000109
Guido van Rossumc6360141990-10-13 19:23:40 +0000110def monthrange(year, month):
Skip Montanaroad3bc442000-08-30 14:01:28 +0000111 """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'
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000115 day1 = weekday(year, month, 1)
116 ndays = mdays[month] + (month == February and isleap(year))
117 return day1, ndays
Guido van Rossumc6360141990-10-13 19:23:40 +0000118
Skip Montanaroad3bc442000-08-30 14:01:28 +0000119def monthcalendar(year, month):
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000120 """Return a matrix representing a month's calendar.
Skip Montanaroad3bc442000-08-30 14:01:28 +0000121 Each row represents a week; days outside this month are zero."""
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000122 day1, ndays = monthrange(year, month)
123 rows = []
124 r7 = range(7)
Skip Montanaroad3bc442000-08-30 14:01:28 +0000125 day = (_firstweekday - day1 + 6) % 7 - 5 # for leading 0's in first week
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000126 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
Guido van Rossumc6360141990-10-13 19:23:40 +0000133
Guido van Rossum9b3bc711993-06-20 21:02:22 +0000134def _center(str, width):
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000135 """Center a string in a field."""
136 n = width - len(str)
Skip Montanaroad3bc442000-08-30 14:01:28 +0000137 if n <= 0:
138 return str
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000139 return ' '*((n+1)/2) + str + ' '*((n)/2)
Guido van Rossumc6360141990-10-13 19:23:40 +0000140
Skip Montanaroad3bc442000-08-30 14:01:28 +0000141def prweek(theweek, width):
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000142 """Print a single week (no newline)."""
Skip Montanaroad3bc442000-08-30 14:01:28 +0000143 print week(theweek, width),
144
145def 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)
Guido van Rossumc6360141990-10-13 19:23:40 +0000155
Guido van Rossumc6360141990-10-13 19:23:40 +0000156def weekheader(width):
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000157 """Return a header for a week."""
Skip Montanaroad3bc442000-08-30 14:01:28 +0000158 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)
Guido van Rossumc6360141990-10-13 19:23:40 +0000166
Skip Montanaroad3bc442000-08-30 14:01:28 +0000167def prmonth(theyear, themonth, w=0, l=0):
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000168 """Print a month's calendar."""
Skip Montanaroad3bc442000-08-30 14:01:28 +0000169 print month(theyear, themonth, w, l),
170
171def month(theyear, themonth, w=0, l=0):
172 """Return a month's calendar string (multi-line)."""
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000173 w = max(2, w)
174 l = max(1, l)
Tim Peters88869f92001-01-14 23:36:06 +0000175 s = (_center(month_name[themonth] + ' ' + `theyear`,
Skip Montanaroad3bc442000-08-30 14:01:28 +0000176 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'
Guido van Rossumc6360141990-10-13 19:23:40 +0000181
Skip Montanaroad3bc442000-08-30 14:01:28 +0000182# Spacing of month columns for 3-column year calendar
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000183_colwidth = 7*3 - 1 # Amount printed by prweek()
Skip Montanaroad3bc442000-08-30 14:01:28 +0000184_spacing = 6 # Number of spaces between columns
Guido van Rossumc6360141990-10-13 19:23:40 +0000185
Skip Montanaroad3bc442000-08-30 14:01:28 +0000186def format3c(a, b, c, colwidth=_colwidth, spacing=_spacing):
187 """Prints 3-column formatting for year calendars"""
188 print format3cstring(a, b, c, colwidth, spacing)
Guido van Rossumc6360141990-10-13 19:23:40 +0000189
Skip Montanaroad3bc442000-08-30 14:01:28 +0000190def 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))
194
195def prcal(year, w=0, l=0, c=_spacing):
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000196 """Print a year's calendar."""
Skip Montanaroad3bc442000-08-30 14:01:28 +0000197 print calendar(year, w, l, c),
198
199def 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()
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000208 for q in range(January, January+12, 3):
Skip Montanaroad3bc442000-08-30 14:01:28 +0000209 s = (s + '\n' * l +
210 format3cstring(month_name[q], month_name[q+1], month_name[q+2],
Tim Peters88869f92001-01-14 23:36:06 +0000211 colwidth, c).rstrip() +
Skip Montanaroad3bc442000-08-30 14:01:28 +0000212 '\n' * l + header + '\n' * l)
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000213 data = []
214 height = 0
Skip Montanaroad3bc442000-08-30 14:01:28 +0000215 for amonth in range(q, q + 3):
216 cal = monthcalendar(year, amonth)
217 if len(cal) > height:
218 height = len(cal)
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000219 data.append(cal)
220 for i in range(height):
Skip Montanaroad3bc442000-08-30 14:01:28 +0000221 weeks = []
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000222 for cal in data:
223 if i >= len(cal):
Skip Montanaroad3bc442000-08-30 14:01:28 +0000224 weeks.append('')
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000225 else:
Skip Montanaroad3bc442000-08-30 14:01:28 +0000226 weeks.append(week(cal[i], w))
Tim Peters88869f92001-01-14 23:36:06 +0000227 s = s + format3cstring(weeks[0], weeks[1], weeks[2],
Skip Montanaroad3bc442000-08-30 14:01:28 +0000228 colwidth, c).rstrip() + '\n' * l
229 return s[:-l] + '\n'
Guido van Rossumb39aff81999-06-09 15:07:38 +0000230
Guido van Rossumb39aff81999-06-09 15:07:38 +0000231EPOCH = 1970
232def timegm(tuple):
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000233 """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