blob: 3f9b7ba9740fe378f58777ce060e7da55e705cf2 [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
Guido van Rossumc6360141990-10-13 19:23:40 +000012
Skip Montanaroe99d5ea2001-01-20 19:54:20 +000013__all__ = ["error","setfirstweekday","firstweekday","isleap",
14 "leapdays","weekday","monthrange","monthcalendar",
Tim Peters0c2c8e72002-03-23 03:26:53 +000015 "prmonth","month","prcal","calendar","timegm",
16 "month_name", "month_abbr", "day_name", "day_abbr"]
Skip Montanaroe99d5ea2001-01-20 19:54:20 +000017
Guido van Rossumc6360141990-10-13 19:23:40 +000018# Exception raised for bad input (with string parameter for details)
Guido van Rossum00245cf1999-05-03 18:07:40 +000019error = ValueError
Guido van Rossumc6360141990-10-13 19:23:40 +000020
Guido van Rossum9b3bc711993-06-20 21:02:22 +000021# Constants for months referenced later
22January = 1
23February = 2
24
25# Number of days per month (except for February in leap years)
26mdays = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
27
Tim Peters0c2c8e72002-03-23 03:26:53 +000028# This module used to have hard-coded lists of day and month names, as
29# English strings. The classes following emulate a read-only version of
30# that, but supply localized names. Note that the values are computed
31# fresh on each call, in case the user changes locale between calls.
32
Raymond Hettinger9c051d72002-06-20 03:38:12 +000033class _localized_month:
Tim Peters0c2c8e72002-03-23 03:26:53 +000034 def __init__(self, format):
Barry Warsaw1d099102001-05-22 15:58:30 +000035 self.format = format
Tim Peters0c2c8e72002-03-23 03:26:53 +000036
37 def __getitem__(self, i):
Raymond Hettingerd058f082002-10-21 03:08:20 +000038 data = [strftime(self.format, (2001, j, 1, 12, 0, 0, 1, 1, 0))
Tim Peters0c2c8e72002-03-23 03:26:53 +000039 for j in range(1, 13)]
Raymond Hettingerd058f082002-10-21 03:08:20 +000040 data.insert(0, "")
41 return data[i]
Tim Peters0c2c8e72002-03-23 03:26:53 +000042
Skip Montanaro4c834952002-03-15 04:08:38 +000043 def __len__(self):
Tim Peters0c2c8e72002-03-23 03:26:53 +000044 return 13
45
Raymond Hettinger9c051d72002-06-20 03:38:12 +000046class _localized_day:
Tim Peters0c2c8e72002-03-23 03:26:53 +000047 def __init__(self, format):
48 self.format = format
49
50 def __getitem__(self, i):
51 # January 1, 2001, was a Monday.
Raymond Hettingerd058f082002-10-21 03:08:20 +000052 data = [strftime(self.format, (2001, 1, j+1, 12, 0, 0, j, j+1, 0))
Tim Peters0c2c8e72002-03-23 03:26:53 +000053 for j in range(7)]
Raymond Hettingerd058f082002-10-21 03:08:20 +000054 return data[i]
Tim Peters0c2c8e72002-03-23 03:26:53 +000055
56 def __len__(self_):
57 return 7
Barry Warsaw1d099102001-05-22 15:58:30 +000058
Guido van Rossum9b3bc711993-06-20 21:02:22 +000059# Full and abbreviated names of weekdays
Tim Peters0c2c8e72002-03-23 03:26:53 +000060day_name = _localized_day('%A')
61day_abbr = _localized_day('%a')
Guido van Rossum9b3bc711993-06-20 21:02:22 +000062
Guido van Rossum5cfa5df1993-06-23 09:30:50 +000063# Full and abbreviated names of months (1-based arrays!!!)
Tim Peters0c2c8e72002-03-23 03:26:53 +000064month_name = _localized_month('%B')
65month_abbr = _localized_month('%b')
Guido van Rossum9b3bc711993-06-20 21:02:22 +000066
Skip Montanaroad3bc442000-08-30 14:01:28 +000067# Constants for weekdays
68(MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY) = range(7)
69
70_firstweekday = 0 # 0 = Monday, 6 = Sunday
71
72def firstweekday():
73 return _firstweekday
74
75def setfirstweekday(weekday):
76 """Set weekday (Monday=0, Sunday=6) to start each week."""
77 global _firstweekday
78 if not MONDAY <= weekday <= SUNDAY:
79 raise ValueError, \
80 'bad weekday number; must be 0 (Monday) to 6 (Sunday)'
81 _firstweekday = weekday
82
Guido van Rossum9b3bc711993-06-20 21:02:22 +000083def isleap(year):
Guido van Rossum4acc25b2000-02-02 15:10:15 +000084 """Return 1 for leap years, 0 for non-leap years."""
Fred Drake8152d322000-12-12 23:20:45 +000085 return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
Guido van Rossum9b3bc711993-06-20 21:02:22 +000086
Guido van Rossum9b3bc711993-06-20 21:02:22 +000087def leapdays(y1, y2):
Guido van Rossum4acc25b2000-02-02 15:10:15 +000088 """Return number of leap years in range [y1, y2).
Guido van Rossum46735ad2000-10-09 12:42:04 +000089 Assume y1 <= y2."""
90 y1 -= 1
91 y2 -= 1
92 return (y2/4 - y1/4) - (y2/100 - y1/100) + (y2/400 - y1/400)
Guido van Rossum9b3bc711993-06-20 21:02:22 +000093
Guido van Rossumc6360141990-10-13 19:23:40 +000094def weekday(year, month, day):
Skip Montanaroad3bc442000-08-30 14:01:28 +000095 """Return weekday (0-6 ~ Mon-Sun) for year (1970-...), month (1-12),
96 day (1-31)."""
Guido van Rossum4acc25b2000-02-02 15:10:15 +000097 secs = mktime((year, month, day, 0, 0, 0, 0, 0, 0))
98 tuple = localtime(secs)
99 return tuple[6]
Guido van Rossumc6360141990-10-13 19:23:40 +0000100
Guido van Rossumc6360141990-10-13 19:23:40 +0000101def monthrange(year, month):
Skip Montanaroad3bc442000-08-30 14:01:28 +0000102 """Return weekday (0-6 ~ Mon-Sun) and number of days (28-31) for
103 year, month."""
104 if not 1 <= month <= 12:
105 raise ValueError, 'bad month number'
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000106 day1 = weekday(year, month, 1)
107 ndays = mdays[month] + (month == February and isleap(year))
108 return day1, ndays
Guido van Rossumc6360141990-10-13 19:23:40 +0000109
Skip Montanaroad3bc442000-08-30 14:01:28 +0000110def monthcalendar(year, month):
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000111 """Return a matrix representing a month's calendar.
Skip Montanaroad3bc442000-08-30 14:01:28 +0000112 Each row represents a week; days outside this month are zero."""
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000113 day1, ndays = monthrange(year, month)
114 rows = []
115 r7 = range(7)
Skip Montanaroad3bc442000-08-30 14:01:28 +0000116 day = (_firstweekday - day1 + 6) % 7 - 5 # for leading 0's in first week
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000117 while day <= ndays:
118 row = [0, 0, 0, 0, 0, 0, 0]
119 for i in r7:
120 if 1 <= day <= ndays: row[i] = day
121 day = day + 1
122 rows.append(row)
123 return rows
Guido van Rossumc6360141990-10-13 19:23:40 +0000124
Skip Montanaroad3bc442000-08-30 14:01:28 +0000125def prweek(theweek, width):
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000126 """Print a single week (no newline)."""
Skip Montanaroad3bc442000-08-30 14:01:28 +0000127 print week(theweek, width),
128
129def week(theweek, width):
130 """Returns a single week in a string (no newline)."""
131 days = []
132 for day in theweek:
133 if day == 0:
134 s = ''
135 else:
136 s = '%2i' % day # right-align single-digit days
Raymond Hettinger9ecf9ce2002-10-22 05:15:17 +0000137 days.append(s.center(width))
Skip Montanaroad3bc442000-08-30 14:01:28 +0000138 return ' '.join(days)
Guido van Rossumc6360141990-10-13 19:23:40 +0000139
Guido van Rossumc6360141990-10-13 19:23:40 +0000140def weekheader(width):
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000141 """Return a header for a week."""
Skip Montanaroad3bc442000-08-30 14:01:28 +0000142 if width >= 9:
143 names = day_name
144 else:
145 names = day_abbr
146 days = []
147 for i in range(_firstweekday, _firstweekday + 7):
Raymond Hettinger9ecf9ce2002-10-22 05:15:17 +0000148 days.append(names[i%7][:width].center(width))
Skip Montanaroad3bc442000-08-30 14:01:28 +0000149 return ' '.join(days)
Guido van Rossumc6360141990-10-13 19:23:40 +0000150
Skip Montanaroad3bc442000-08-30 14:01:28 +0000151def prmonth(theyear, themonth, w=0, l=0):
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000152 """Print a month's calendar."""
Skip Montanaroad3bc442000-08-30 14:01:28 +0000153 print month(theyear, themonth, w, l),
154
155def month(theyear, themonth, w=0, l=0):
156 """Return a month's calendar string (multi-line)."""
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000157 w = max(2, w)
158 l = max(1, l)
Raymond Hettinger9ecf9ce2002-10-22 05:15:17 +0000159 s = ((month_name[themonth] + ' ' + `theyear`).center(
Skip Montanaroad3bc442000-08-30 14:01:28 +0000160 7 * (w + 1) - 1).rstrip() +
161 '\n' * l + weekheader(w).rstrip() + '\n' * l)
162 for aweek in monthcalendar(theyear, themonth):
163 s = s + week(aweek, w).rstrip() + '\n' * l
164 return s[:-l] + '\n'
Guido van Rossumc6360141990-10-13 19:23:40 +0000165
Skip Montanaroad3bc442000-08-30 14:01:28 +0000166# Spacing of month columns for 3-column year calendar
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000167_colwidth = 7*3 - 1 # Amount printed by prweek()
Skip Montanaroad3bc442000-08-30 14:01:28 +0000168_spacing = 6 # Number of spaces between columns
Guido van Rossumc6360141990-10-13 19:23:40 +0000169
Skip Montanaroad3bc442000-08-30 14:01:28 +0000170def format3c(a, b, c, colwidth=_colwidth, spacing=_spacing):
171 """Prints 3-column formatting for year calendars"""
172 print format3cstring(a, b, c, colwidth, spacing)
Guido van Rossumc6360141990-10-13 19:23:40 +0000173
Skip Montanaroad3bc442000-08-30 14:01:28 +0000174def format3cstring(a, b, c, colwidth=_colwidth, spacing=_spacing):
175 """Returns a string formatted from 3 strings, centered within 3 columns."""
Raymond Hettinger9ecf9ce2002-10-22 05:15:17 +0000176 return (a.center(colwidth) + ' ' * spacing + b.center(colwidth) +
177 ' ' * spacing + c.center(colwidth))
Skip Montanaroad3bc442000-08-30 14:01:28 +0000178
179def prcal(year, w=0, l=0, c=_spacing):
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000180 """Print a year's calendar."""
Skip Montanaroad3bc442000-08-30 14:01:28 +0000181 print calendar(year, w, l, c),
182
183def calendar(year, w=0, l=0, c=_spacing):
184 """Returns a year's calendar as a multi-line string."""
185 w = max(2, w)
186 l = max(1, l)
187 c = max(2, c)
188 colwidth = (w + 1) * 7 - 1
Raymond Hettinger9ecf9ce2002-10-22 05:15:17 +0000189 s = `year`.center(colwidth * 3 + c * 2).rstrip() + '\n' * l
Skip Montanaroad3bc442000-08-30 14:01:28 +0000190 header = weekheader(w)
191 header = format3cstring(header, header, header, colwidth, c).rstrip()
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000192 for q in range(January, January+12, 3):
Skip Montanaroad3bc442000-08-30 14:01:28 +0000193 s = (s + '\n' * l +
194 format3cstring(month_name[q], month_name[q+1], month_name[q+2],
Tim Peters88869f92001-01-14 23:36:06 +0000195 colwidth, c).rstrip() +
Skip Montanaroad3bc442000-08-30 14:01:28 +0000196 '\n' * l + header + '\n' * l)
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000197 data = []
198 height = 0
Skip Montanaroad3bc442000-08-30 14:01:28 +0000199 for amonth in range(q, q + 3):
200 cal = monthcalendar(year, amonth)
201 if len(cal) > height:
202 height = len(cal)
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000203 data.append(cal)
204 for i in range(height):
Skip Montanaroad3bc442000-08-30 14:01:28 +0000205 weeks = []
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000206 for cal in data:
207 if i >= len(cal):
Skip Montanaroad3bc442000-08-30 14:01:28 +0000208 weeks.append('')
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000209 else:
Skip Montanaroad3bc442000-08-30 14:01:28 +0000210 weeks.append(week(cal[i], w))
Tim Peters88869f92001-01-14 23:36:06 +0000211 s = s + format3cstring(weeks[0], weeks[1], weeks[2],
Skip Montanaroad3bc442000-08-30 14:01:28 +0000212 colwidth, c).rstrip() + '\n' * l
213 return s[:-l] + '\n'
Guido van Rossumb39aff81999-06-09 15:07:38 +0000214
Guido van Rossumb39aff81999-06-09 15:07:38 +0000215EPOCH = 1970
216def timegm(tuple):
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000217 """Unrelated but handy function to calculate Unix timestamp from GMT."""
218 year, month, day, hour, minute, second = tuple[:6]
219 assert year >= EPOCH
220 assert 1 <= month <= 12
221 days = 365*(year-EPOCH) + leapdays(EPOCH, year)
222 for i in range(1, month):
223 days = days + mdays[i]
224 if month > 2 and isleap(year):
225 days = days + 1
226 days = days + day - 1
227 hours = days*24 + hour
228 minutes = hours*60 + minute
229 seconds = minutes*60 + second
230 return seconds