]>
Commit | Line | Data |
---|---|---|
3257aa99 DM |
1 | """Calendar printing functions\r |
2 | \r | |
3 | Note when comparing these calendars to the ones printed by cal(1): By\r | |
4 | default, these calendars have Monday as the first day of the week, and\r | |
5 | Sunday as the last (the European convention). Use setfirstweekday() to\r | |
6 | set the first day of the week (0=Monday, 6=Sunday)."""\r | |
7 | \r | |
8 | import sys\r | |
9 | import datetime\r | |
10 | import locale as _locale\r | |
11 | \r | |
12 | __all__ = ["IllegalMonthError", "IllegalWeekdayError", "setfirstweekday",\r | |
13 | "firstweekday", "isleap", "leapdays", "weekday", "monthrange",\r | |
14 | "monthcalendar", "prmonth", "month", "prcal", "calendar",\r | |
15 | "timegm", "month_name", "month_abbr", "day_name", "day_abbr"]\r | |
16 | \r | |
17 | # Exception raised for bad input (with string parameter for details)\r | |
18 | error = ValueError\r | |
19 | \r | |
20 | # Exceptions raised for bad input\r | |
21 | class IllegalMonthError(ValueError):\r | |
22 | def __init__(self, month):\r | |
23 | self.month = month\r | |
24 | def __str__(self):\r | |
25 | return "bad month number %r; must be 1-12" % self.month\r | |
26 | \r | |
27 | \r | |
28 | class IllegalWeekdayError(ValueError):\r | |
29 | def __init__(self, weekday):\r | |
30 | self.weekday = weekday\r | |
31 | def __str__(self):\r | |
32 | return "bad weekday number %r; must be 0 (Monday) to 6 (Sunday)" % self.weekday\r | |
33 | \r | |
34 | \r | |
35 | # Constants for months referenced later\r | |
36 | January = 1\r | |
37 | February = 2\r | |
38 | \r | |
39 | # Number of days per month (except for February in leap years)\r | |
40 | mdays = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\r | |
41 | \r | |
42 | # This module used to have hard-coded lists of day and month names, as\r | |
43 | # English strings. The classes following emulate a read-only version of\r | |
44 | # that, but supply localized names. Note that the values are computed\r | |
45 | # fresh on each call, in case the user changes locale between calls.\r | |
46 | \r | |
47 | class _localized_month:\r | |
48 | \r | |
49 | _months = [datetime.date(2001, i+1, 1).strftime for i in range(12)]\r | |
50 | _months.insert(0, lambda x: "")\r | |
51 | \r | |
52 | def __init__(self, format):\r | |
53 | self.format = format\r | |
54 | \r | |
55 | def __getitem__(self, i):\r | |
56 | funcs = self._months[i]\r | |
57 | if isinstance(i, slice):\r | |
58 | return [f(self.format) for f in funcs]\r | |
59 | else:\r | |
60 | return funcs(self.format)\r | |
61 | \r | |
62 | def __len__(self):\r | |
63 | return 13\r | |
64 | \r | |
65 | \r | |
66 | class _localized_day:\r | |
67 | \r | |
68 | # January 1, 2001, was a Monday.\r | |
69 | _days = [datetime.date(2001, 1, i+1).strftime for i in range(7)]\r | |
70 | \r | |
71 | def __init__(self, format):\r | |
72 | self.format = format\r | |
73 | \r | |
74 | def __getitem__(self, i):\r | |
75 | funcs = self._days[i]\r | |
76 | if isinstance(i, slice):\r | |
77 | return [f(self.format) for f in funcs]\r | |
78 | else:\r | |
79 | return funcs(self.format)\r | |
80 | \r | |
81 | def __len__(self):\r | |
82 | return 7\r | |
83 | \r | |
84 | \r | |
85 | # Full and abbreviated names of weekdays\r | |
86 | day_name = _localized_day('%A')\r | |
87 | day_abbr = _localized_day('%a')\r | |
88 | \r | |
89 | # Full and abbreviated names of months (1-based arrays!!!)\r | |
90 | month_name = _localized_month('%B')\r | |
91 | month_abbr = _localized_month('%b')\r | |
92 | \r | |
93 | # Constants for weekdays\r | |
94 | (MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY) = range(7)\r | |
95 | \r | |
96 | \r | |
97 | def isleap(year):\r | |
98 | """Return True for leap years, False for non-leap years."""\r | |
99 | return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)\r | |
100 | \r | |
101 | \r | |
102 | def leapdays(y1, y2):\r | |
103 | """Return number of leap years in range [y1, y2).\r | |
104 | Assume y1 <= y2."""\r | |
105 | y1 -= 1\r | |
106 | y2 -= 1\r | |
107 | return (y2//4 - y1//4) - (y2//100 - y1//100) + (y2//400 - y1//400)\r | |
108 | \r | |
109 | \r | |
110 | def weekday(year, month, day):\r | |
111 | """Return weekday (0-6 ~ Mon-Sun) for year (1970-...), month (1-12),\r | |
112 | day (1-31)."""\r | |
113 | return datetime.date(year, month, day).weekday()\r | |
114 | \r | |
115 | \r | |
116 | def monthrange(year, month):\r | |
117 | """Return weekday (0-6 ~ Mon-Sun) and number of days (28-31) for\r | |
118 | year, month."""\r | |
119 | if not 1 <= month <= 12:\r | |
120 | raise IllegalMonthError(month)\r | |
121 | day1 = weekday(year, month, 1)\r | |
122 | ndays = mdays[month] + (month == February and isleap(year))\r | |
123 | return day1, ndays\r | |
124 | \r | |
125 | \r | |
126 | class Calendar(object):\r | |
127 | """\r | |
128 | Base calendar class. This class doesn't do any formatting. It simply\r | |
129 | provides data to subclasses.\r | |
130 | """\r | |
131 | \r | |
132 | def __init__(self, firstweekday=0):\r | |
133 | self.firstweekday = firstweekday # 0 = Monday, 6 = Sunday\r | |
134 | \r | |
135 | def getfirstweekday(self):\r | |
136 | return self._firstweekday % 7\r | |
137 | \r | |
138 | def setfirstweekday(self, firstweekday):\r | |
139 | self._firstweekday = firstweekday\r | |
140 | \r | |
141 | firstweekday = property(getfirstweekday, setfirstweekday)\r | |
142 | \r | |
143 | def iterweekdays(self):\r | |
144 | """\r | |
145 | Return a iterator for one week of weekday numbers starting with the\r | |
146 | configured first one.\r | |
147 | """\r | |
148 | for i in range(self.firstweekday, self.firstweekday + 7):\r | |
149 | yield i%7\r | |
150 | \r | |
151 | def itermonthdates(self, year, month):\r | |
152 | """\r | |
153 | Return an iterator for one month. The iterator will yield datetime.date\r | |
154 | values and will always iterate through complete weeks, so it will yield\r | |
155 | dates outside the specified month.\r | |
156 | """\r | |
157 | date = datetime.date(year, month, 1)\r | |
158 | # Go back to the beginning of the week\r | |
159 | days = (date.weekday() - self.firstweekday) % 7\r | |
160 | date -= datetime.timedelta(days=days)\r | |
161 | oneday = datetime.timedelta(days=1)\r | |
162 | while True:\r | |
163 | yield date\r | |
164 | try:\r | |
165 | date += oneday\r | |
166 | except OverflowError:\r | |
167 | # Adding one day could fail after datetime.MAXYEAR\r | |
168 | break\r | |
169 | if date.month != month and date.weekday() == self.firstweekday:\r | |
170 | break\r | |
171 | \r | |
172 | def itermonthdays2(self, year, month):\r | |
173 | """\r | |
174 | Like itermonthdates(), but will yield (day number, weekday number)\r | |
175 | tuples. For days outside the specified month the day number is 0.\r | |
176 | """\r | |
177 | for date in self.itermonthdates(year, month):\r | |
178 | if date.month != month:\r | |
179 | yield (0, date.weekday())\r | |
180 | else:\r | |
181 | yield (date.day, date.weekday())\r | |
182 | \r | |
183 | def itermonthdays(self, year, month):\r | |
184 | """\r | |
185 | Like itermonthdates(), but will yield day numbers. For days outside\r | |
186 | the specified month the day number is 0.\r | |
187 | """\r | |
188 | for date in self.itermonthdates(year, month):\r | |
189 | if date.month != month:\r | |
190 | yield 0\r | |
191 | else:\r | |
192 | yield date.day\r | |
193 | \r | |
194 | def monthdatescalendar(self, year, month):\r | |
195 | """\r | |
196 | Return a matrix (list of lists) representing a month's calendar.\r | |
197 | Each row represents a week; week entries are datetime.date values.\r | |
198 | """\r | |
199 | dates = list(self.itermonthdates(year, month))\r | |
200 | return [ dates[i:i+7] for i in range(0, len(dates), 7) ]\r | |
201 | \r | |
202 | def monthdays2calendar(self, year, month):\r | |
203 | """\r | |
204 | Return a matrix representing a month's calendar.\r | |
205 | Each row represents a week; week entries are\r | |
206 | (day number, weekday number) tuples. Day numbers outside this month\r | |
207 | are zero.\r | |
208 | """\r | |
209 | days = list(self.itermonthdays2(year, month))\r | |
210 | return [ days[i:i+7] for i in range(0, len(days), 7) ]\r | |
211 | \r | |
212 | def monthdayscalendar(self, year, month):\r | |
213 | """\r | |
214 | Return a matrix representing a month's calendar.\r | |
215 | Each row represents a week; days outside this month are zero.\r | |
216 | """\r | |
217 | days = list(self.itermonthdays(year, month))\r | |
218 | return [ days[i:i+7] for i in range(0, len(days), 7) ]\r | |
219 | \r | |
220 | def yeardatescalendar(self, year, width=3):\r | |
221 | """\r | |
222 | Return the data for the specified year ready for formatting. The return\r | |
223 | value is a list of month rows. Each month row contains up to width months.\r | |
224 | Each month contains between 4 and 6 weeks and each week contains 1-7\r | |
225 | days. Days are datetime.date objects.\r | |
226 | """\r | |
227 | months = [\r | |
228 | self.monthdatescalendar(year, i)\r | |
229 | for i in range(January, January+12)\r | |
230 | ]\r | |
231 | return [months[i:i+width] for i in range(0, len(months), width) ]\r | |
232 | \r | |
233 | def yeardays2calendar(self, year, width=3):\r | |
234 | """\r | |
235 | Return the data for the specified year ready for formatting (similar to\r | |
236 | yeardatescalendar()). Entries in the week lists are\r | |
237 | (day number, weekday number) tuples. Day numbers outside this month are\r | |
238 | zero.\r | |
239 | """\r | |
240 | months = [\r | |
241 | self.monthdays2calendar(year, i)\r | |
242 | for i in range(January, January+12)\r | |
243 | ]\r | |
244 | return [months[i:i+width] for i in range(0, len(months), width) ]\r | |
245 | \r | |
246 | def yeardayscalendar(self, year, width=3):\r | |
247 | """\r | |
248 | Return the data for the specified year ready for formatting (similar to\r | |
249 | yeardatescalendar()). Entries in the week lists are day numbers.\r | |
250 | Day numbers outside this month are zero.\r | |
251 | """\r | |
252 | months = [\r | |
253 | self.monthdayscalendar(year, i)\r | |
254 | for i in range(January, January+12)\r | |
255 | ]\r | |
256 | return [months[i:i+width] for i in range(0, len(months), width) ]\r | |
257 | \r | |
258 | \r | |
259 | class TextCalendar(Calendar):\r | |
260 | """\r | |
261 | Subclass of Calendar that outputs a calendar as a simple plain text\r | |
262 | similar to the UNIX program cal.\r | |
263 | """\r | |
264 | \r | |
265 | def prweek(self, theweek, width):\r | |
266 | """\r | |
267 | Print a single week (no newline).\r | |
268 | """\r | |
269 | print self.formatweek(theweek, width),\r | |
270 | \r | |
271 | def formatday(self, day, weekday, width):\r | |
272 | """\r | |
273 | Returns a formatted day.\r | |
274 | """\r | |
275 | if day == 0:\r | |
276 | s = ''\r | |
277 | else:\r | |
278 | s = '%2i' % day # right-align single-digit days\r | |
279 | return s.center(width)\r | |
280 | \r | |
281 | def formatweek(self, theweek, width):\r | |
282 | """\r | |
283 | Returns a single week in a string (no newline).\r | |
284 | """\r | |
285 | return ' '.join(self.formatday(d, wd, width) for (d, wd) in theweek)\r | |
286 | \r | |
287 | def formatweekday(self, day, width):\r | |
288 | """\r | |
289 | Returns a formatted week day name.\r | |
290 | """\r | |
291 | if width >= 9:\r | |
292 | names = day_name\r | |
293 | else:\r | |
294 | names = day_abbr\r | |
295 | return names[day][:width].center(width)\r | |
296 | \r | |
297 | def formatweekheader(self, width):\r | |
298 | """\r | |
299 | Return a header for a week.\r | |
300 | """\r | |
301 | return ' '.join(self.formatweekday(i, width) for i in self.iterweekdays())\r | |
302 | \r | |
303 | def formatmonthname(self, theyear, themonth, width, withyear=True):\r | |
304 | """\r | |
305 | Return a formatted month name.\r | |
306 | """\r | |
307 | s = month_name[themonth]\r | |
308 | if withyear:\r | |
309 | s = "%s %r" % (s, theyear)\r | |
310 | return s.center(width)\r | |
311 | \r | |
312 | def prmonth(self, theyear, themonth, w=0, l=0):\r | |
313 | """\r | |
314 | Print a month's calendar.\r | |
315 | """\r | |
316 | print self.formatmonth(theyear, themonth, w, l),\r | |
317 | \r | |
318 | def formatmonth(self, theyear, themonth, w=0, l=0):\r | |
319 | """\r | |
320 | Return a month's calendar string (multi-line).\r | |
321 | """\r | |
322 | w = max(2, w)\r | |
323 | l = max(1, l)\r | |
324 | s = self.formatmonthname(theyear, themonth, 7 * (w + 1) - 1)\r | |
325 | s = s.rstrip()\r | |
326 | s += '\n' * l\r | |
327 | s += self.formatweekheader(w).rstrip()\r | |
328 | s += '\n' * l\r | |
329 | for week in self.monthdays2calendar(theyear, themonth):\r | |
330 | s += self.formatweek(week, w).rstrip()\r | |
331 | s += '\n' * l\r | |
332 | return s\r | |
333 | \r | |
334 | def formatyear(self, theyear, w=2, l=1, c=6, m=3):\r | |
335 | """\r | |
336 | Returns a year's calendar as a multi-line string.\r | |
337 | """\r | |
338 | w = max(2, w)\r | |
339 | l = max(1, l)\r | |
340 | c = max(2, c)\r | |
341 | colwidth = (w + 1) * 7 - 1\r | |
342 | v = []\r | |
343 | a = v.append\r | |
344 | a(repr(theyear).center(colwidth*m+c*(m-1)).rstrip())\r | |
345 | a('\n'*l)\r | |
346 | header = self.formatweekheader(w)\r | |
347 | for (i, row) in enumerate(self.yeardays2calendar(theyear, m)):\r | |
348 | # months in this row\r | |
349 | months = range(m*i+1, min(m*(i+1)+1, 13))\r | |
350 | a('\n'*l)\r | |
351 | names = (self.formatmonthname(theyear, k, colwidth, False)\r | |
352 | for k in months)\r | |
353 | a(formatstring(names, colwidth, c).rstrip())\r | |
354 | a('\n'*l)\r | |
355 | headers = (header for k in months)\r | |
356 | a(formatstring(headers, colwidth, c).rstrip())\r | |
357 | a('\n'*l)\r | |
358 | # max number of weeks for this row\r | |
359 | height = max(len(cal) for cal in row)\r | |
360 | for j in range(height):\r | |
361 | weeks = []\r | |
362 | for cal in row:\r | |
363 | if j >= len(cal):\r | |
364 | weeks.append('')\r | |
365 | else:\r | |
366 | weeks.append(self.formatweek(cal[j], w))\r | |
367 | a(formatstring(weeks, colwidth, c).rstrip())\r | |
368 | a('\n' * l)\r | |
369 | return ''.join(v)\r | |
370 | \r | |
371 | def pryear(self, theyear, w=0, l=0, c=6, m=3):\r | |
372 | """Print a year's calendar."""\r | |
373 | print self.formatyear(theyear, w, l, c, m)\r | |
374 | \r | |
375 | \r | |
376 | class HTMLCalendar(Calendar):\r | |
377 | """\r | |
378 | This calendar returns complete HTML pages.\r | |
379 | """\r | |
380 | \r | |
381 | # CSS classes for the day <td>s\r | |
382 | cssclasses = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"]\r | |
383 | \r | |
384 | def formatday(self, day, weekday):\r | |
385 | """\r | |
386 | Return a day as a table cell.\r | |
387 | """\r | |
388 | if day == 0:\r | |
389 | return '<td class="noday"> </td>' # day outside month\r | |
390 | else:\r | |
391 | return '<td class="%s">%d</td>' % (self.cssclasses[weekday], day)\r | |
392 | \r | |
393 | def formatweek(self, theweek):\r | |
394 | """\r | |
395 | Return a complete week as a table row.\r | |
396 | """\r | |
397 | s = ''.join(self.formatday(d, wd) for (d, wd) in theweek)\r | |
398 | return '<tr>%s</tr>' % s\r | |
399 | \r | |
400 | def formatweekday(self, day):\r | |
401 | """\r | |
402 | Return a weekday name as a table header.\r | |
403 | """\r | |
404 | return '<th class="%s">%s</th>' % (self.cssclasses[day], day_abbr[day])\r | |
405 | \r | |
406 | def formatweekheader(self):\r | |
407 | """\r | |
408 | Return a header for a week as a table row.\r | |
409 | """\r | |
410 | s = ''.join(self.formatweekday(i) for i in self.iterweekdays())\r | |
411 | return '<tr>%s</tr>' % s\r | |
412 | \r | |
413 | def formatmonthname(self, theyear, themonth, withyear=True):\r | |
414 | """\r | |
415 | Return a month name as a table row.\r | |
416 | """\r | |
417 | if withyear:\r | |
418 | s = '%s %s' % (month_name[themonth], theyear)\r | |
419 | else:\r | |
420 | s = '%s' % month_name[themonth]\r | |
421 | return '<tr><th colspan="7" class="month">%s</th></tr>' % s\r | |
422 | \r | |
423 | def formatmonth(self, theyear, themonth, withyear=True):\r | |
424 | """\r | |
425 | Return a formatted month as a table.\r | |
426 | """\r | |
427 | v = []\r | |
428 | a = v.append\r | |
429 | a('<table border="0" cellpadding="0" cellspacing="0" class="month">')\r | |
430 | a('\n')\r | |
431 | a(self.formatmonthname(theyear, themonth, withyear=withyear))\r | |
432 | a('\n')\r | |
433 | a(self.formatweekheader())\r | |
434 | a('\n')\r | |
435 | for week in self.monthdays2calendar(theyear, themonth):\r | |
436 | a(self.formatweek(week))\r | |
437 | a('\n')\r | |
438 | a('</table>')\r | |
439 | a('\n')\r | |
440 | return ''.join(v)\r | |
441 | \r | |
442 | def formatyear(self, theyear, width=3):\r | |
443 | """\r | |
444 | Return a formatted year as a table of tables.\r | |
445 | """\r | |
446 | v = []\r | |
447 | a = v.append\r | |
448 | width = max(width, 1)\r | |
449 | a('<table border="0" cellpadding="0" cellspacing="0" class="year">')\r | |
450 | a('\n')\r | |
451 | a('<tr><th colspan="%d" class="year">%s</th></tr>' % (width, theyear))\r | |
452 | for i in range(January, January+12, width):\r | |
453 | # months in this row\r | |
454 | months = range(i, min(i+width, 13))\r | |
455 | a('<tr>')\r | |
456 | for m in months:\r | |
457 | a('<td>')\r | |
458 | a(self.formatmonth(theyear, m, withyear=False))\r | |
459 | a('</td>')\r | |
460 | a('</tr>')\r | |
461 | a('</table>')\r | |
462 | return ''.join(v)\r | |
463 | \r | |
464 | def formatyearpage(self, theyear, width=3, css='calendar.css', encoding=None):\r | |
465 | """\r | |
466 | Return a formatted year as a complete HTML page.\r | |
467 | """\r | |
468 | if encoding is None:\r | |
469 | encoding = sys.getdefaultencoding()\r | |
470 | v = []\r | |
471 | a = v.append\r | |
472 | a('<?xml version="1.0" encoding="%s"?>\n' % encoding)\r | |
473 | a('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n')\r | |
474 | a('<html>\n')\r | |
475 | a('<head>\n')\r | |
476 | a('<meta http-equiv="Content-Type" content="text/html; charset=%s" />\n' % encoding)\r | |
477 | if css is not None:\r | |
478 | a('<link rel="stylesheet" type="text/css" href="%s" />\n' % css)\r | |
479 | a('<title>Calendar for %d</title>\n' % theyear)\r | |
480 | a('</head>\n')\r | |
481 | a('<body>\n')\r | |
482 | a(self.formatyear(theyear, width))\r | |
483 | a('</body>\n')\r | |
484 | a('</html>\n')\r | |
485 | return ''.join(v).encode(encoding, "xmlcharrefreplace")\r | |
486 | \r | |
487 | \r | |
488 | class TimeEncoding:\r | |
489 | def __init__(self, locale):\r | |
490 | self.locale = locale\r | |
491 | \r | |
492 | def __enter__(self):\r | |
493 | self.oldlocale = _locale.getlocale(_locale.LC_TIME)\r | |
494 | _locale.setlocale(_locale.LC_TIME, self.locale)\r | |
495 | return _locale.getlocale(_locale.LC_TIME)[1]\r | |
496 | \r | |
497 | def __exit__(self, *args):\r | |
498 | _locale.setlocale(_locale.LC_TIME, self.oldlocale)\r | |
499 | \r | |
500 | \r | |
501 | class LocaleTextCalendar(TextCalendar):\r | |
502 | """\r | |
503 | This class can be passed a locale name in the constructor and will return\r | |
504 | month and weekday names in the specified locale. If this locale includes\r | |
505 | an encoding all strings containing month and weekday names will be returned\r | |
506 | as unicode.\r | |
507 | """\r | |
508 | \r | |
509 | def __init__(self, firstweekday=0, locale=None):\r | |
510 | TextCalendar.__init__(self, firstweekday)\r | |
511 | if locale is None:\r | |
512 | locale = _locale.getdefaultlocale()\r | |
513 | self.locale = locale\r | |
514 | \r | |
515 | def formatweekday(self, day, width):\r | |
516 | with TimeEncoding(self.locale) as encoding:\r | |
517 | if width >= 9:\r | |
518 | names = day_name\r | |
519 | else:\r | |
520 | names = day_abbr\r | |
521 | name = names[day]\r | |
522 | if encoding is not None:\r | |
523 | name = name.decode(encoding)\r | |
524 | return name[:width].center(width)\r | |
525 | \r | |
526 | def formatmonthname(self, theyear, themonth, width, withyear=True):\r | |
527 | with TimeEncoding(self.locale) as encoding:\r | |
528 | s = month_name[themonth]\r | |
529 | if encoding is not None:\r | |
530 | s = s.decode(encoding)\r | |
531 | if withyear:\r | |
532 | s = "%s %r" % (s, theyear)\r | |
533 | return s.center(width)\r | |
534 | \r | |
535 | \r | |
536 | class LocaleHTMLCalendar(HTMLCalendar):\r | |
537 | """\r | |
538 | This class can be passed a locale name in the constructor and will return\r | |
539 | month and weekday names in the specified locale. If this locale includes\r | |
540 | an encoding all strings containing month and weekday names will be returned\r | |
541 | as unicode.\r | |
542 | """\r | |
543 | def __init__(self, firstweekday=0, locale=None):\r | |
544 | HTMLCalendar.__init__(self, firstweekday)\r | |
545 | if locale is None:\r | |
546 | locale = _locale.getdefaultlocale()\r | |
547 | self.locale = locale\r | |
548 | \r | |
549 | def formatweekday(self, day):\r | |
550 | with TimeEncoding(self.locale) as encoding:\r | |
551 | s = day_abbr[day]\r | |
552 | if encoding is not None:\r | |
553 | s = s.decode(encoding)\r | |
554 | return '<th class="%s">%s</th>' % (self.cssclasses[day], s)\r | |
555 | \r | |
556 | def formatmonthname(self, theyear, themonth, withyear=True):\r | |
557 | with TimeEncoding(self.locale) as encoding:\r | |
558 | s = month_name[themonth]\r | |
559 | if encoding is not None:\r | |
560 | s = s.decode(encoding)\r | |
561 | if withyear:\r | |
562 | s = '%s %s' % (s, theyear)\r | |
563 | return '<tr><th colspan="7" class="month">%s</th></tr>' % s\r | |
564 | \r | |
565 | \r | |
566 | # Support for old module level interface\r | |
567 | c = TextCalendar()\r | |
568 | \r | |
569 | firstweekday = c.getfirstweekday\r | |
570 | \r | |
571 | def setfirstweekday(firstweekday):\r | |
572 | try:\r | |
573 | firstweekday.__index__\r | |
574 | except AttributeError:\r | |
575 | raise IllegalWeekdayError(firstweekday)\r | |
576 | if not MONDAY <= firstweekday <= SUNDAY:\r | |
577 | raise IllegalWeekdayError(firstweekday)\r | |
578 | c.firstweekday = firstweekday\r | |
579 | \r | |
580 | monthcalendar = c.monthdayscalendar\r | |
581 | prweek = c.prweek\r | |
582 | week = c.formatweek\r | |
583 | weekheader = c.formatweekheader\r | |
584 | prmonth = c.prmonth\r | |
585 | month = c.formatmonth\r | |
586 | calendar = c.formatyear\r | |
587 | prcal = c.pryear\r | |
588 | \r | |
589 | \r | |
590 | # Spacing of month columns for multi-column year calendar\r | |
591 | _colwidth = 7*3 - 1 # Amount printed by prweek()\r | |
592 | _spacing = 6 # Number of spaces between columns\r | |
593 | \r | |
594 | \r | |
595 | def format(cols, colwidth=_colwidth, spacing=_spacing):\r | |
596 | """Prints multi-column formatting for year calendars"""\r | |
597 | print formatstring(cols, colwidth, spacing)\r | |
598 | \r | |
599 | \r | |
600 | def formatstring(cols, colwidth=_colwidth, spacing=_spacing):\r | |
601 | """Returns a string formatted from n strings, centered within n columns."""\r | |
602 | spacing *= ' '\r | |
603 | return spacing.join(c.center(colwidth) for c in cols)\r | |
604 | \r | |
605 | \r | |
606 | EPOCH = 1970\r | |
607 | _EPOCH_ORD = datetime.date(EPOCH, 1, 1).toordinal()\r | |
608 | \r | |
609 | \r | |
610 | def timegm(tuple):\r | |
611 | """Unrelated but handy function to calculate Unix timestamp from GMT."""\r | |
612 | year, month, day, hour, minute, second = tuple[:6]\r | |
613 | days = datetime.date(year, month, 1).toordinal() - _EPOCH_ORD + day - 1\r | |
614 | hours = days*24 + hour\r | |
615 | minutes = hours*60 + minute\r | |
616 | seconds = minutes*60 + second\r | |
617 | return seconds\r | |
618 | \r | |
619 | \r | |
620 | def main(args):\r | |
621 | import optparse\r | |
622 | parser = optparse.OptionParser(usage="usage: %prog [options] [year [month]]")\r | |
623 | parser.add_option(\r | |
624 | "-w", "--width",\r | |
625 | dest="width", type="int", default=2,\r | |
626 | help="width of date column (default 2, text only)"\r | |
627 | )\r | |
628 | parser.add_option(\r | |
629 | "-l", "--lines",\r | |
630 | dest="lines", type="int", default=1,\r | |
631 | help="number of lines for each week (default 1, text only)"\r | |
632 | )\r | |
633 | parser.add_option(\r | |
634 | "-s", "--spacing",\r | |
635 | dest="spacing", type="int", default=6,\r | |
636 | help="spacing between months (default 6, text only)"\r | |
637 | )\r | |
638 | parser.add_option(\r | |
639 | "-m", "--months",\r | |
640 | dest="months", type="int", default=3,\r | |
641 | help="months per row (default 3, text only)"\r | |
642 | )\r | |
643 | parser.add_option(\r | |
644 | "-c", "--css",\r | |
645 | dest="css", default="calendar.css",\r | |
646 | help="CSS to use for page (html only)"\r | |
647 | )\r | |
648 | parser.add_option(\r | |
649 | "-L", "--locale",\r | |
650 | dest="locale", default=None,\r | |
651 | help="locale to be used from month and weekday names"\r | |
652 | )\r | |
653 | parser.add_option(\r | |
654 | "-e", "--encoding",\r | |
655 | dest="encoding", default=None,\r | |
656 | help="Encoding to use for output"\r | |
657 | )\r | |
658 | parser.add_option(\r | |
659 | "-t", "--type",\r | |
660 | dest="type", default="text",\r | |
661 | choices=("text", "html"),\r | |
662 | help="output type (text or html)"\r | |
663 | )\r | |
664 | \r | |
665 | (options, args) = parser.parse_args(args)\r | |
666 | \r | |
667 | if options.locale and not options.encoding:\r | |
668 | parser.error("if --locale is specified --encoding is required")\r | |
669 | sys.exit(1)\r | |
670 | \r | |
671 | locale = options.locale, options.encoding\r | |
672 | \r | |
673 | if options.type == "html":\r | |
674 | if options.locale:\r | |
675 | cal = LocaleHTMLCalendar(locale=locale)\r | |
676 | else:\r | |
677 | cal = HTMLCalendar()\r | |
678 | encoding = options.encoding\r | |
679 | if encoding is None:\r | |
680 | encoding = sys.getdefaultencoding()\r | |
681 | optdict = dict(encoding=encoding, css=options.css)\r | |
682 | if len(args) == 1:\r | |
683 | print cal.formatyearpage(datetime.date.today().year, **optdict)\r | |
684 | elif len(args) == 2:\r | |
685 | print cal.formatyearpage(int(args[1]), **optdict)\r | |
686 | else:\r | |
687 | parser.error("incorrect number of arguments")\r | |
688 | sys.exit(1)\r | |
689 | else:\r | |
690 | if options.locale:\r | |
691 | cal = LocaleTextCalendar(locale=locale)\r | |
692 | else:\r | |
693 | cal = TextCalendar()\r | |
694 | optdict = dict(w=options.width, l=options.lines)\r | |
695 | if len(args) != 3:\r | |
696 | optdict["c"] = options.spacing\r | |
697 | optdict["m"] = options.months\r | |
698 | if len(args) == 1:\r | |
699 | result = cal.formatyear(datetime.date.today().year, **optdict)\r | |
700 | elif len(args) == 2:\r | |
701 | result = cal.formatyear(int(args[1]), **optdict)\r | |
702 | elif len(args) == 3:\r | |
703 | result = cal.formatmonth(int(args[1]), int(args[2]), **optdict)\r | |
704 | else:\r | |
705 | parser.error("incorrect number of arguments")\r | |
706 | sys.exit(1)\r | |
707 | if options.encoding:\r | |
708 | result = result.encode(options.encoding)\r | |
709 | print result\r | |
710 | \r | |
711 | \r | |
712 | if __name__ == "__main__":\r | |
713 | main(sys.argv)\r |