calendar.py 25 KB

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