blob: 3ffcff5957e2a1bb3445e6fda135502d2886a426 [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
Raymond Hettingere11b5102002-12-25 16:37:19 +00008import datetime
Guido van Rossumc6360141990-10-13 19:23:40 +00009
Skip Montanaroe99d5ea2001-01-20 19:54:20 +000010__all__ = ["error","setfirstweekday","firstweekday","isleap",
11 "leapdays","weekday","monthrange","monthcalendar",
Tim Peters0c2c8e72002-03-23 03:26:53 +000012 "prmonth","month","prcal","calendar","timegm",
Raymond Hettinger77d08bc2005-05-10 03:20:12 +000013 "month_name", "month_abbr", "day_name", "day_abbr",
14 "weekheader"]
Skip Montanaroe99d5ea2001-01-20 19:54:20 +000015
Guido van Rossumc6360141990-10-13 19:23:40 +000016# Exception raised for bad input (with string parameter for details)
Guido van Rossum00245cf1999-05-03 18:07:40 +000017error = ValueError
Guido van Rossumc6360141990-10-13 19:23:40 +000018
Guido van Rossum9b3bc711993-06-20 21:02:22 +000019# Constants for months referenced later
20January = 1
21February = 2
22
23# Number of days per month (except for February in leap years)
24mdays = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
25
Tim Peters0c2c8e72002-03-23 03:26:53 +000026# This module used to have hard-coded lists of day and month names, as
27# English strings. The classes following emulate a read-only version of
28# that, but supply localized names. Note that the values are computed
29# fresh on each call, in case the user changes locale between calls.
30
Raymond Hettinger9c051d72002-06-20 03:38:12 +000031class _localized_month:
Tim Petersbbc0d442004-11-13 16:18:32 +000032
33 _months = [datetime.date(2001, i+1, 1).strftime for i in range(12)]
34 _months.insert(0, lambda x: "")
35
Tim Peters0c2c8e72002-03-23 03:26:53 +000036 def __init__(self, format):
Barry Warsaw1d099102001-05-22 15:58:30 +000037 self.format = format
Tim Peters0c2c8e72002-03-23 03:26:53 +000038
39 def __getitem__(self, i):
Tim Petersbbc0d442004-11-13 16:18:32 +000040 funcs = self._months[i]
41 if isinstance(i, slice):
42 return [f(self.format) for f in funcs]
43 else:
44 return funcs(self.format)
Tim Peters0c2c8e72002-03-23 03:26:53 +000045
Skip Montanaro4c834952002-03-15 04:08:38 +000046 def __len__(self):
Tim Peters0c2c8e72002-03-23 03:26:53 +000047 return 13
48
Raymond Hettinger9c051d72002-06-20 03:38:12 +000049class _localized_day:
Tim Petersbbc0d442004-11-13 16:18:32 +000050
51 # January 1, 2001, was a Monday.
52 _days = [datetime.date(2001, 1, i+1).strftime for i in range(7)]
53
Tim Peters0c2c8e72002-03-23 03:26:53 +000054 def __init__(self, format):
55 self.format = format
56
57 def __getitem__(self, i):
Tim Petersbbc0d442004-11-13 16:18:32 +000058 funcs = self._days[i]
59 if isinstance(i, slice):
60 return [f(self.format) for f in funcs]
61 else:
62 return funcs(self.format)
Tim Peters0c2c8e72002-03-23 03:26:53 +000063
Neal Norwitz492faa52004-06-07 03:47:06 +000064 def __len__(self):
Tim Peters0c2c8e72002-03-23 03:26:53 +000065 return 7
Barry Warsaw1d099102001-05-22 15:58:30 +000066
Guido van Rossum9b3bc711993-06-20 21:02:22 +000067# Full and abbreviated names of weekdays
Tim Peters0c2c8e72002-03-23 03:26:53 +000068day_name = _localized_day('%A')
69day_abbr = _localized_day('%a')
Guido van Rossum9b3bc711993-06-20 21:02:22 +000070
Guido van Rossum5cfa5df1993-06-23 09:30:50 +000071# Full and abbreviated names of months (1-based arrays!!!)
Tim Peters0c2c8e72002-03-23 03:26:53 +000072month_name = _localized_month('%B')
73month_abbr = _localized_month('%b')
Guido van Rossum9b3bc711993-06-20 21:02:22 +000074
Skip Montanaroad3bc442000-08-30 14:01:28 +000075# Constants for weekdays
76(MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY) = range(7)
77
78_firstweekday = 0 # 0 = Monday, 6 = Sunday
79
80def firstweekday():
81 return _firstweekday
82
83def setfirstweekday(weekday):
84 """Set weekday (Monday=0, Sunday=6) to start each week."""
85 global _firstweekday
86 if not MONDAY <= weekday <= SUNDAY:
87 raise ValueError, \
88 'bad weekday number; must be 0 (Monday) to 6 (Sunday)'
89 _firstweekday = weekday
90
Guido van Rossum9b3bc711993-06-20 21:02:22 +000091def isleap(year):
Guido van Rossum4acc25b2000-02-02 15:10:15 +000092 """Return 1 for leap years, 0 for non-leap years."""
Fred Drake8152d322000-12-12 23:20:45 +000093 return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
Guido van Rossum9b3bc711993-06-20 21:02:22 +000094
Guido van Rossum9b3bc711993-06-20 21:02:22 +000095def leapdays(y1, y2):
Guido van Rossum4acc25b2000-02-02 15:10:15 +000096 """Return number of leap years in range [y1, y2).
Guido van Rossum46735ad2000-10-09 12:42:04 +000097 Assume y1 <= y2."""
98 y1 -= 1
99 y2 -= 1
Raymond Hettingere11b5102002-12-25 16:37:19 +0000100 return (y2//4 - y1//4) - (y2//100 - y1//100) + (y2//400 - y1//400)
Guido van Rossum9b3bc711993-06-20 21:02:22 +0000101
Guido van Rossumc6360141990-10-13 19:23:40 +0000102def weekday(year, month, day):
Skip Montanaroad3bc442000-08-30 14:01:28 +0000103 """Return weekday (0-6 ~ Mon-Sun) for year (1970-...), month (1-12),
104 day (1-31)."""
Raymond Hettingere11b5102002-12-25 16:37:19 +0000105 return datetime.date(year, month, day).weekday()
Guido van Rossumc6360141990-10-13 19:23:40 +0000106
Guido van Rossumc6360141990-10-13 19:23:40 +0000107def monthrange(year, month):
Skip Montanaroad3bc442000-08-30 14:01:28 +0000108 """Return weekday (0-6 ~ Mon-Sun) and number of days (28-31) for
109 year, month."""
110 if not 1 <= month <= 12:
111 raise ValueError, 'bad month number'
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000112 day1 = weekday(year, month, 1)
113 ndays = mdays[month] + (month == February and isleap(year))
114 return day1, ndays
Guido van Rossumc6360141990-10-13 19:23:40 +0000115
Skip Montanaroad3bc442000-08-30 14:01:28 +0000116def monthcalendar(year, month):
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000117 """Return a matrix representing a month's calendar.
Skip Montanaroad3bc442000-08-30 14:01:28 +0000118 Each row represents a week; days outside this month are zero."""
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000119 day1, ndays = monthrange(year, month)
120 rows = []
121 r7 = range(7)
Skip Montanaroad3bc442000-08-30 14:01:28 +0000122 day = (_firstweekday - day1 + 6) % 7 - 5 # for leading 0's in first week
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000123 while day <= ndays:
124 row = [0, 0, 0, 0, 0, 0, 0]
125 for i in r7:
126 if 1 <= day <= ndays: row[i] = day
127 day = day + 1
128 rows.append(row)
129 return rows
Guido van Rossumc6360141990-10-13 19:23:40 +0000130
Skip Montanaroad3bc442000-08-30 14:01:28 +0000131def prweek(theweek, width):
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000132 """Print a single week (no newline)."""
Skip Montanaroad3bc442000-08-30 14:01:28 +0000133 print week(theweek, width),
134
135def week(theweek, width):
136 """Returns a single week in a string (no newline)."""
137 days = []
138 for day in theweek:
139 if day == 0:
140 s = ''
141 else:
142 s = '%2i' % day # right-align single-digit days
Raymond Hettinger9ecf9ce2002-10-22 05:15:17 +0000143 days.append(s.center(width))
Skip Montanaroad3bc442000-08-30 14:01:28 +0000144 return ' '.join(days)
Guido van Rossumc6360141990-10-13 19:23:40 +0000145
Guido van Rossumc6360141990-10-13 19:23:40 +0000146def weekheader(width):
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000147 """Return a header for a week."""
Skip Montanaroad3bc442000-08-30 14:01:28 +0000148 if width >= 9:
149 names = day_name
150 else:
151 names = day_abbr
152 days = []
153 for i in range(_firstweekday, _firstweekday + 7):
Raymond Hettinger9ecf9ce2002-10-22 05:15:17 +0000154 days.append(names[i%7][:width].center(width))
Skip Montanaroad3bc442000-08-30 14:01:28 +0000155 return ' '.join(days)
Guido van Rossumc6360141990-10-13 19:23:40 +0000156
Skip Montanaroad3bc442000-08-30 14:01:28 +0000157def prmonth(theyear, themonth, w=0, l=0):
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000158 """Print a month's calendar."""
Skip Montanaroad3bc442000-08-30 14:01:28 +0000159 print month(theyear, themonth, w, l),
160
161def month(theyear, themonth, w=0, l=0):
162 """Return a month's calendar string (multi-line)."""
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000163 w = max(2, w)
164 l = max(1, l)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000165 s = ("%s %r" % (month_name[themonth], theyear)).center(
166 7 * (w + 1) - 1).rstrip() + \
167 '\n' * l + weekheader(w).rstrip() + '\n' * l
Skip Montanaroad3bc442000-08-30 14:01:28 +0000168 for aweek in monthcalendar(theyear, themonth):
169 s = s + week(aweek, w).rstrip() + '\n' * l
170 return s[:-l] + '\n'
Guido van Rossumc6360141990-10-13 19:23:40 +0000171
Skip Montanaroad3bc442000-08-30 14:01:28 +0000172# Spacing of month columns for 3-column year calendar
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000173_colwidth = 7*3 - 1 # Amount printed by prweek()
Skip Montanaroad3bc442000-08-30 14:01:28 +0000174_spacing = 6 # Number of spaces between columns
Guido van Rossumc6360141990-10-13 19:23:40 +0000175
Skip Montanaroad3bc442000-08-30 14:01:28 +0000176def format3c(a, b, c, colwidth=_colwidth, spacing=_spacing):
177 """Prints 3-column formatting for year calendars"""
178 print format3cstring(a, b, c, colwidth, spacing)
Guido van Rossumc6360141990-10-13 19:23:40 +0000179
Skip Montanaroad3bc442000-08-30 14:01:28 +0000180def format3cstring(a, b, c, colwidth=_colwidth, spacing=_spacing):
181 """Returns a string formatted from 3 strings, centered within 3 columns."""
Raymond Hettinger9ecf9ce2002-10-22 05:15:17 +0000182 return (a.center(colwidth) + ' ' * spacing + b.center(colwidth) +
183 ' ' * spacing + c.center(colwidth))
Skip Montanaroad3bc442000-08-30 14:01:28 +0000184
185def prcal(year, w=0, l=0, c=_spacing):
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000186 """Print a year's calendar."""
Skip Montanaroad3bc442000-08-30 14:01:28 +0000187 print calendar(year, w, l, c),
188
189def calendar(year, w=0, l=0, c=_spacing):
190 """Returns a year's calendar as a multi-line string."""
191 w = max(2, w)
192 l = max(1, l)
193 c = max(2, c)
194 colwidth = (w + 1) * 7 - 1
Walter Dörwald70a6b492004-02-12 17:35:32 +0000195 s = repr(year).center(colwidth * 3 + c * 2).rstrip() + '\n' * l
Skip Montanaroad3bc442000-08-30 14:01:28 +0000196 header = weekheader(w)
197 header = format3cstring(header, header, header, colwidth, c).rstrip()
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000198 for q in range(January, January+12, 3):
Skip Montanaroad3bc442000-08-30 14:01:28 +0000199 s = (s + '\n' * l +
200 format3cstring(month_name[q], month_name[q+1], month_name[q+2],
Tim Peters88869f92001-01-14 23:36:06 +0000201 colwidth, c).rstrip() +
Skip Montanaroad3bc442000-08-30 14:01:28 +0000202 '\n' * l + header + '\n' * l)
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000203 data = []
204 height = 0
Skip Montanaroad3bc442000-08-30 14:01:28 +0000205 for amonth in range(q, q + 3):
206 cal = monthcalendar(year, amonth)
207 if len(cal) > height:
208 height = len(cal)
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000209 data.append(cal)
210 for i in range(height):
Skip Montanaroad3bc442000-08-30 14:01:28 +0000211 weeks = []
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000212 for cal in data:
213 if i >= len(cal):
Skip Montanaroad3bc442000-08-30 14:01:28 +0000214 weeks.append('')
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000215 else:
Skip Montanaroad3bc442000-08-30 14:01:28 +0000216 weeks.append(week(cal[i], w))
Tim Peters88869f92001-01-14 23:36:06 +0000217 s = s + format3cstring(weeks[0], weeks[1], weeks[2],
Skip Montanaroad3bc442000-08-30 14:01:28 +0000218 colwidth, c).rstrip() + '\n' * l
219 return s[:-l] + '\n'
Guido van Rossumb39aff81999-06-09 15:07:38 +0000220
Guido van Rossumb39aff81999-06-09 15:07:38 +0000221EPOCH = 1970
Raymond Hettingere11b5102002-12-25 16:37:19 +0000222_EPOCH_ORD = datetime.date(EPOCH, 1, 1).toordinal()
223
Guido van Rossumb39aff81999-06-09 15:07:38 +0000224def timegm(tuple):
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000225 """Unrelated but handy function to calculate Unix timestamp from GMT."""
226 year, month, day, hour, minute, second = tuple[:6]
Raymond Hettinger61436482003-02-13 22:58:02 +0000227 days = datetime.date(year, month, 1).toordinal() - _EPOCH_ORD + day - 1
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000228 hours = days*24 + hour
229 minutes = hours*60 + minute
230 seconds = minutes*60 + second
231 return seconds