blob: fb56826f6fb62ffca73829fa93b01371443f7fcd [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",
13 "month_name", "month_abbr", "day_name", "day_abbr"]
Skip Montanaroe99d5ea2001-01-20 19:54:20 +000014
Guido van Rossumc6360141990-10-13 19:23:40 +000015# Exception raised for bad input (with string parameter for details)
Guido van Rossum00245cf1999-05-03 18:07:40 +000016error = ValueError
Guido van Rossumc6360141990-10-13 19:23:40 +000017
Guido van Rossum9b3bc711993-06-20 21:02:22 +000018# Constants for months referenced later
19January = 1
20February = 2
21
22# Number of days per month (except for February in leap years)
23mdays = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
24
Tim Peters0c2c8e72002-03-23 03:26:53 +000025# This module used to have hard-coded lists of day and month names, as
26# English strings. The classes following emulate a read-only version of
27# that, but supply localized names. Note that the values are computed
28# fresh on each call, in case the user changes locale between calls.
29
Raymond Hettinger9c051d72002-06-20 03:38:12 +000030class _localized_month:
Tim Peters0c2c8e72002-03-23 03:26:53 +000031 def __init__(self, format):
Barry Warsaw1d099102001-05-22 15:58:30 +000032 self.format = format
Tim Peters0c2c8e72002-03-23 03:26:53 +000033
34 def __getitem__(self, i):
Raymond Hettingere11b5102002-12-25 16:37:19 +000035 data = [datetime.date(2001, j, 1).strftime(self.format)
Tim Peters0c2c8e72002-03-23 03:26:53 +000036 for j in range(1, 13)]
Raymond Hettingerd058f082002-10-21 03:08:20 +000037 data.insert(0, "")
38 return data[i]
Tim Peters0c2c8e72002-03-23 03:26:53 +000039
Skip Montanaro4c834952002-03-15 04:08:38 +000040 def __len__(self):
Tim Peters0c2c8e72002-03-23 03:26:53 +000041 return 13
42
Raymond Hettinger9c051d72002-06-20 03:38:12 +000043class _localized_day:
Tim Peters0c2c8e72002-03-23 03:26:53 +000044 def __init__(self, format):
45 self.format = format
46
47 def __getitem__(self, i):
48 # January 1, 2001, was a Monday.
Raymond Hettingere11b5102002-12-25 16:37:19 +000049 data = [datetime.date(2001, 1, j+1).strftime(self.format)
Tim Peters0c2c8e72002-03-23 03:26:53 +000050 for j in range(7)]
Raymond Hettingerd058f082002-10-21 03:08:20 +000051 return data[i]
Tim Peters0c2c8e72002-03-23 03:26:53 +000052
53 def __len__(self_):
54 return 7
Barry Warsaw1d099102001-05-22 15:58:30 +000055
Guido van Rossum9b3bc711993-06-20 21:02:22 +000056# Full and abbreviated names of weekdays
Tim Peters0c2c8e72002-03-23 03:26:53 +000057day_name = _localized_day('%A')
58day_abbr = _localized_day('%a')
Guido van Rossum9b3bc711993-06-20 21:02:22 +000059
Guido van Rossum5cfa5df1993-06-23 09:30:50 +000060# Full and abbreviated names of months (1-based arrays!!!)
Tim Peters0c2c8e72002-03-23 03:26:53 +000061month_name = _localized_month('%B')
62month_abbr = _localized_month('%b')
Guido van Rossum9b3bc711993-06-20 21:02:22 +000063
Skip Montanaroad3bc442000-08-30 14:01:28 +000064# Constants for weekdays
65(MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY) = range(7)
66
67_firstweekday = 0 # 0 = Monday, 6 = Sunday
68
69def firstweekday():
70 return _firstweekday
71
72def setfirstweekday(weekday):
73 """Set weekday (Monday=0, Sunday=6) to start each week."""
74 global _firstweekday
75 if not MONDAY <= weekday <= SUNDAY:
76 raise ValueError, \
77 'bad weekday number; must be 0 (Monday) to 6 (Sunday)'
78 _firstweekday = weekday
79
Guido van Rossum9b3bc711993-06-20 21:02:22 +000080def isleap(year):
Guido van Rossum4acc25b2000-02-02 15:10:15 +000081 """Return 1 for leap years, 0 for non-leap years."""
Fred Drake8152d322000-12-12 23:20:45 +000082 return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
Guido van Rossum9b3bc711993-06-20 21:02:22 +000083
Guido van Rossum9b3bc711993-06-20 21:02:22 +000084def leapdays(y1, y2):
Guido van Rossum4acc25b2000-02-02 15:10:15 +000085 """Return number of leap years in range [y1, y2).
Guido van Rossum46735ad2000-10-09 12:42:04 +000086 Assume y1 <= y2."""
87 y1 -= 1
88 y2 -= 1
Raymond Hettingere11b5102002-12-25 16:37:19 +000089 return (y2//4 - y1//4) - (y2//100 - y1//100) + (y2//400 - y1//400)
Guido van Rossum9b3bc711993-06-20 21:02:22 +000090
Guido van Rossumc6360141990-10-13 19:23:40 +000091def weekday(year, month, day):
Skip Montanaroad3bc442000-08-30 14:01:28 +000092 """Return weekday (0-6 ~ Mon-Sun) for year (1970-...), month (1-12),
93 day (1-31)."""
Raymond Hettingere11b5102002-12-25 16:37:19 +000094 return datetime.date(year, month, day).weekday()
Guido van Rossumc6360141990-10-13 19:23:40 +000095
Guido van Rossumc6360141990-10-13 19:23:40 +000096def monthrange(year, month):
Skip Montanaroad3bc442000-08-30 14:01:28 +000097 """Return weekday (0-6 ~ Mon-Sun) and number of days (28-31) for
98 year, month."""
99 if not 1 <= month <= 12:
100 raise ValueError, 'bad month number'
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000101 day1 = weekday(year, month, 1)
102 ndays = mdays[month] + (month == February and isleap(year))
103 return day1, ndays
Guido van Rossumc6360141990-10-13 19:23:40 +0000104
Skip Montanaroad3bc442000-08-30 14:01:28 +0000105def monthcalendar(year, month):
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000106 """Return a matrix representing a month's calendar.
Skip Montanaroad3bc442000-08-30 14:01:28 +0000107 Each row represents a week; days outside this month are zero."""
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000108 day1, ndays = monthrange(year, month)
109 rows = []
110 r7 = range(7)
Skip Montanaroad3bc442000-08-30 14:01:28 +0000111 day = (_firstweekday - day1 + 6) % 7 - 5 # for leading 0's in first week
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000112 while day <= ndays:
113 row = [0, 0, 0, 0, 0, 0, 0]
114 for i in r7:
115 if 1 <= day <= ndays: row[i] = day
116 day = day + 1
117 rows.append(row)
118 return rows
Guido van Rossumc6360141990-10-13 19:23:40 +0000119
Skip Montanaroad3bc442000-08-30 14:01:28 +0000120def prweek(theweek, width):
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000121 """Print a single week (no newline)."""
Skip Montanaroad3bc442000-08-30 14:01:28 +0000122 print week(theweek, width),
123
124def week(theweek, width):
125 """Returns a single week in a string (no newline)."""
126 days = []
127 for day in theweek:
128 if day == 0:
129 s = ''
130 else:
131 s = '%2i' % day # right-align single-digit days
Raymond Hettinger9ecf9ce2002-10-22 05:15:17 +0000132 days.append(s.center(width))
Skip Montanaroad3bc442000-08-30 14:01:28 +0000133 return ' '.join(days)
Guido van Rossumc6360141990-10-13 19:23:40 +0000134
Guido van Rossumc6360141990-10-13 19:23:40 +0000135def weekheader(width):
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000136 """Return a header for a week."""
Skip Montanaroad3bc442000-08-30 14:01:28 +0000137 if width >= 9:
138 names = day_name
139 else:
140 names = day_abbr
141 days = []
142 for i in range(_firstweekday, _firstweekday + 7):
Raymond Hettinger9ecf9ce2002-10-22 05:15:17 +0000143 days.append(names[i%7][:width].center(width))
Skip Montanaroad3bc442000-08-30 14:01:28 +0000144 return ' '.join(days)
Guido van Rossumc6360141990-10-13 19:23:40 +0000145
Skip Montanaroad3bc442000-08-30 14:01:28 +0000146def prmonth(theyear, themonth, w=0, l=0):
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000147 """Print a month's calendar."""
Skip Montanaroad3bc442000-08-30 14:01:28 +0000148 print month(theyear, themonth, w, l),
149
150def month(theyear, themonth, w=0, l=0):
151 """Return a month's calendar string (multi-line)."""
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000152 w = max(2, w)
153 l = max(1, l)
Raymond Hettinger9ecf9ce2002-10-22 05:15:17 +0000154 s = ((month_name[themonth] + ' ' + `theyear`).center(
Skip Montanaroad3bc442000-08-30 14:01:28 +0000155 7 * (w + 1) - 1).rstrip() +
156 '\n' * l + weekheader(w).rstrip() + '\n' * l)
157 for aweek in monthcalendar(theyear, themonth):
158 s = s + week(aweek, w).rstrip() + '\n' * l
159 return s[:-l] + '\n'
Guido van Rossumc6360141990-10-13 19:23:40 +0000160
Skip Montanaroad3bc442000-08-30 14:01:28 +0000161# Spacing of month columns for 3-column year calendar
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000162_colwidth = 7*3 - 1 # Amount printed by prweek()
Skip Montanaroad3bc442000-08-30 14:01:28 +0000163_spacing = 6 # Number of spaces between columns
Guido van Rossumc6360141990-10-13 19:23:40 +0000164
Skip Montanaroad3bc442000-08-30 14:01:28 +0000165def format3c(a, b, c, colwidth=_colwidth, spacing=_spacing):
166 """Prints 3-column formatting for year calendars"""
167 print format3cstring(a, b, c, colwidth, spacing)
Guido van Rossumc6360141990-10-13 19:23:40 +0000168
Skip Montanaroad3bc442000-08-30 14:01:28 +0000169def format3cstring(a, b, c, colwidth=_colwidth, spacing=_spacing):
170 """Returns a string formatted from 3 strings, centered within 3 columns."""
Raymond Hettinger9ecf9ce2002-10-22 05:15:17 +0000171 return (a.center(colwidth) + ' ' * spacing + b.center(colwidth) +
172 ' ' * spacing + c.center(colwidth))
Skip Montanaroad3bc442000-08-30 14:01:28 +0000173
174def prcal(year, w=0, l=0, c=_spacing):
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000175 """Print a year's calendar."""
Skip Montanaroad3bc442000-08-30 14:01:28 +0000176 print calendar(year, w, l, c),
177
178def calendar(year, w=0, l=0, c=_spacing):
179 """Returns a year's calendar as a multi-line string."""
180 w = max(2, w)
181 l = max(1, l)
182 c = max(2, c)
183 colwidth = (w + 1) * 7 - 1
Raymond Hettinger9ecf9ce2002-10-22 05:15:17 +0000184 s = `year`.center(colwidth * 3 + c * 2).rstrip() + '\n' * l
Skip Montanaroad3bc442000-08-30 14:01:28 +0000185 header = weekheader(w)
186 header = format3cstring(header, header, header, colwidth, c).rstrip()
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000187 for q in range(January, January+12, 3):
Skip Montanaroad3bc442000-08-30 14:01:28 +0000188 s = (s + '\n' * l +
189 format3cstring(month_name[q], month_name[q+1], month_name[q+2],
Tim Peters88869f92001-01-14 23:36:06 +0000190 colwidth, c).rstrip() +
Skip Montanaroad3bc442000-08-30 14:01:28 +0000191 '\n' * l + header + '\n' * l)
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000192 data = []
193 height = 0
Skip Montanaroad3bc442000-08-30 14:01:28 +0000194 for amonth in range(q, q + 3):
195 cal = monthcalendar(year, amonth)
196 if len(cal) > height:
197 height = len(cal)
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000198 data.append(cal)
199 for i in range(height):
Skip Montanaroad3bc442000-08-30 14:01:28 +0000200 weeks = []
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000201 for cal in data:
202 if i >= len(cal):
Skip Montanaroad3bc442000-08-30 14:01:28 +0000203 weeks.append('')
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000204 else:
Skip Montanaroad3bc442000-08-30 14:01:28 +0000205 weeks.append(week(cal[i], w))
Tim Peters88869f92001-01-14 23:36:06 +0000206 s = s + format3cstring(weeks[0], weeks[1], weeks[2],
Skip Montanaroad3bc442000-08-30 14:01:28 +0000207 colwidth, c).rstrip() + '\n' * l
208 return s[:-l] + '\n'
Guido van Rossumb39aff81999-06-09 15:07:38 +0000209
Guido van Rossumb39aff81999-06-09 15:07:38 +0000210EPOCH = 1970
Raymond Hettingere11b5102002-12-25 16:37:19 +0000211_EPOCH_ORD = datetime.date(EPOCH, 1, 1).toordinal()
212
Guido van Rossumb39aff81999-06-09 15:07:38 +0000213def timegm(tuple):
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000214 """Unrelated but handy function to calculate Unix timestamp from GMT."""
215 year, month, day, hour, minute, second = tuple[:6]
Raymond Hettinger61436482003-02-13 22:58:02 +0000216 days = datetime.date(year, month, 1).toordinal() - _EPOCH_ORD + day - 1
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000217 hours = days*24 + hour
218 minutes = hours*60 + minute
219 seconds = minutes*60 + second
220 return seconds