calendar.py 25 KB

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