blob: b0834c9621d430bb569ec42bf429931501ea80cf [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):
38 self.data = [strftime(self.format, (2001, j, 1, 12, 0, 0, 1, 1, 0))
39 for j in range(1, 13)]
40 self.data.insert(0, "")
Raymond Hettinger9c051d72002-06-20 03:38:12 +000041 return self.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.
52 self.data = [strftime(self.format, (2001, 1, j+1, 12, 0, 0, j, j+1, 0))
53 for j in range(7)]
Raymond Hettinger9c051d72002-06-20 03:38:12 +000054 return self.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
Guido van Rossum9b3bc711993-06-20 21:02:22 +0000125def _center(str, width):
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000126 """Center a string in a field."""
127 n = width - len(str)
Skip Montanaroad3bc442000-08-30 14:01:28 +0000128 if n <= 0:
129 return str
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000130 return ' '*((n+1)/2) + str + ' '*((n)/2)
Guido van Rossumc6360141990-10-13 19:23:40 +0000131
Skip Montanaroad3bc442000-08-30 14:01:28 +0000132def prweek(theweek, width):
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000133 """Print a single week (no newline)."""
Skip Montanaroad3bc442000-08-30 14:01:28 +0000134 print week(theweek, width),
135
136def week(theweek, width):
137 """Returns a single week in a string (no newline)."""
138 days = []
139 for day in theweek:
140 if day == 0:
141 s = ''
142 else:
143 s = '%2i' % day # right-align single-digit days
144 days.append(_center(s, width))
145 return ' '.join(days)
Guido van Rossumc6360141990-10-13 19:23:40 +0000146
Guido van Rossumc6360141990-10-13 19:23:40 +0000147def weekheader(width):
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000148 """Return a header for a week."""
Skip Montanaroad3bc442000-08-30 14:01:28 +0000149 if width >= 9:
150 names = day_name
151 else:
152 names = day_abbr
153 days = []
154 for i in range(_firstweekday, _firstweekday + 7):
155 days.append(_center(names[i%7][:width], width))
156 return ' '.join(days)
Guido van Rossumc6360141990-10-13 19:23:40 +0000157
Skip Montanaroad3bc442000-08-30 14:01:28 +0000158def prmonth(theyear, themonth, w=0, l=0):
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000159 """Print a month's calendar."""
Skip Montanaroad3bc442000-08-30 14:01:28 +0000160 print month(theyear, themonth, w, l),
161
162def month(theyear, themonth, w=0, l=0):
163 """Return a month's calendar string (multi-line)."""
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000164 w = max(2, w)
165 l = max(1, l)
Tim Peters88869f92001-01-14 23:36:06 +0000166 s = (_center(month_name[themonth] + ' ' + `theyear`,
Skip Montanaroad3bc442000-08-30 14:01:28 +0000167 7 * (w + 1) - 1).rstrip() +
168 '\n' * l + weekheader(w).rstrip() + '\n' * l)
169 for aweek in monthcalendar(theyear, themonth):
170 s = s + week(aweek, w).rstrip() + '\n' * l
171 return s[:-l] + '\n'
Guido van Rossumc6360141990-10-13 19:23:40 +0000172
Skip Montanaroad3bc442000-08-30 14:01:28 +0000173# Spacing of month columns for 3-column year calendar
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000174_colwidth = 7*3 - 1 # Amount printed by prweek()
Skip Montanaroad3bc442000-08-30 14:01:28 +0000175_spacing = 6 # Number of spaces between columns
Guido van Rossumc6360141990-10-13 19:23:40 +0000176
Skip Montanaroad3bc442000-08-30 14:01:28 +0000177def format3c(a, b, c, colwidth=_colwidth, spacing=_spacing):
178 """Prints 3-column formatting for year calendars"""
179 print format3cstring(a, b, c, colwidth, spacing)
Guido van Rossumc6360141990-10-13 19:23:40 +0000180
Skip Montanaroad3bc442000-08-30 14:01:28 +0000181def format3cstring(a, b, c, colwidth=_colwidth, spacing=_spacing):
182 """Returns a string formatted from 3 strings, centered within 3 columns."""
183 return (_center(a, colwidth) + ' ' * spacing + _center(b, colwidth) +
184 ' ' * spacing + _center(c, colwidth))
185
186def prcal(year, w=0, l=0, c=_spacing):
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000187 """Print a year's calendar."""
Skip Montanaroad3bc442000-08-30 14:01:28 +0000188 print calendar(year, w, l, c),
189
190def calendar(year, w=0, l=0, c=_spacing):
191 """Returns a year's calendar as a multi-line string."""
192 w = max(2, w)
193 l = max(1, l)
194 c = max(2, c)
195 colwidth = (w + 1) * 7 - 1
196 s = _center(`year`, colwidth * 3 + c * 2).rstrip() + '\n' * l
197 header = weekheader(w)
198 header = format3cstring(header, header, header, colwidth, c).rstrip()
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000199 for q in range(January, January+12, 3):
Skip Montanaroad3bc442000-08-30 14:01:28 +0000200 s = (s + '\n' * l +
201 format3cstring(month_name[q], month_name[q+1], month_name[q+2],
Tim Peters88869f92001-01-14 23:36:06 +0000202 colwidth, c).rstrip() +
Skip Montanaroad3bc442000-08-30 14:01:28 +0000203 '\n' * l + header + '\n' * l)
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000204 data = []
205 height = 0
Skip Montanaroad3bc442000-08-30 14:01:28 +0000206 for amonth in range(q, q + 3):
207 cal = monthcalendar(year, amonth)
208 if len(cal) > height:
209 height = len(cal)
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000210 data.append(cal)
211 for i in range(height):
Skip Montanaroad3bc442000-08-30 14:01:28 +0000212 weeks = []
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000213 for cal in data:
214 if i >= len(cal):
Skip Montanaroad3bc442000-08-30 14:01:28 +0000215 weeks.append('')
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000216 else:
Skip Montanaroad3bc442000-08-30 14:01:28 +0000217 weeks.append(week(cal[i], w))
Tim Peters88869f92001-01-14 23:36:06 +0000218 s = s + format3cstring(weeks[0], weeks[1], weeks[2],
Skip Montanaroad3bc442000-08-30 14:01:28 +0000219 colwidth, c).rstrip() + '\n' * l
220 return s[:-l] + '\n'
Guido van Rossumb39aff81999-06-09 15:07:38 +0000221
Guido van Rossumb39aff81999-06-09 15:07:38 +0000222EPOCH = 1970
223def timegm(tuple):
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000224 """Unrelated but handy function to calculate Unix timestamp from GMT."""
225 year, month, day, hour, minute, second = tuple[:6]
226 assert year >= EPOCH
227 assert 1 <= month <= 12
228 days = 365*(year-EPOCH) + leapdays(EPOCH, year)
229 for i in range(1, month):
230 days = days + mdays[i]
231 if month > 2 and isleap(year):
232 days = days + 1
233 days = days + day - 1
234 hours = days*24 + hour
235 minutes = hours*60 + minute
236 seconds = minutes*60 + second
237 return seconds