/Lib/calendar.py

http://unladen-swallow.googlecode.com/ · Python · 704 lines · 566 code · 35 blank · 103 comment · 17 complexity · 5c2fa451bb3831b389251f0b3adabc03 MD5 · raw file

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