calendar.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  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 datetime
  7. __all__ = ["error","setfirstweekday","firstweekday","isleap",
  8. "leapdays","weekday","monthrange","monthcalendar",
  9. "prmonth","month","prcal","calendar","timegm",
  10. "month_name", "month_abbr", "day_name", "day_abbr",
  11. "weekheader"]
  12. # Exception raised for bad input (with string parameter for details)
  13. error = ValueError
  14. # Constants for months referenced later
  15. January = 1
  16. February = 2
  17. # Number of days per month (except for February in leap years)
  18. mdays = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
  19. # This module used to have hard-coded lists of day and month names, as
  20. # English strings. The classes following emulate a read-only version of
  21. # that, but supply localized names. Note that the values are computed
  22. # fresh on each call, in case the user changes locale between calls.
  23. class _localized_month:
  24. _months = [datetime.date(2001, i+1, 1).strftime for i in range(12)]
  25. _months.insert(0, lambda x: "")
  26. def __init__(self, format):
  27. self.format = format
  28. def __getitem__(self, i):
  29. funcs = self._months[i]
  30. if isinstance(i, slice):
  31. return [f(self.format) for f in funcs]
  32. else:
  33. return funcs(self.format)
  34. def __len__(self):
  35. return 13
  36. class _localized_day:
  37. # January 1, 2001, was a Monday.
  38. _days = [datetime.date(2001, 1, i+1).strftime for i in range(7)]
  39. def __init__(self, format):
  40. self.format = format
  41. def __getitem__(self, i):
  42. funcs = self._days[i]
  43. if isinstance(i, slice):
  44. return [f(self.format) for f in funcs]
  45. else:
  46. return funcs(self.format)
  47. def __len__(self):
  48. return 7
  49. # Full and abbreviated names of weekdays
  50. day_name = _localized_day('%A')
  51. day_abbr = _localized_day('%a')
  52. # Full and abbreviated names of months (1-based arrays!!!)
  53. month_name = _localized_month('%B')
  54. month_abbr = _localized_month('%b')
  55. # Constants for weekdays
  56. (MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY) = range(7)
  57. _firstweekday = 0 # 0 = Monday, 6 = Sunday
  58. def firstweekday():
  59. return _firstweekday
  60. def setfirstweekday(weekday):
  61. """Set weekday (Monday=0, Sunday=6) to start each week."""
  62. global _firstweekday
  63. if not MONDAY <= weekday <= SUNDAY:
  64. raise ValueError, \
  65. 'bad weekday number; must be 0 (Monday) to 6 (Sunday)'
  66. _firstweekday = weekday
  67. def isleap(year):
  68. """Return 1 for leap years, 0 for non-leap years."""
  69. return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
  70. def leapdays(y1, y2):
  71. """Return number of leap years in range [y1, y2).
  72. Assume y1 <= y2."""
  73. y1 -= 1
  74. y2 -= 1
  75. return (y2//4 - y1//4) - (y2//100 - y1//100) + (y2//400 - y1//400)
  76. def weekday(year, month, day):
  77. """Return weekday (0-6 ~ Mon-Sun) for year (1970-...), month (1-12),
  78. day (1-31)."""
  79. return datetime.date(year, month, day).weekday()
  80. def monthrange(year, month):
  81. """Return weekday (0-6 ~ Mon-Sun) and number of days (28-31) for
  82. year, month."""
  83. if not 1 <= month <= 12:
  84. raise ValueError, 'bad month number'
  85. day1 = weekday(year, month, 1)
  86. ndays = mdays[month] + (month == February and isleap(year))
  87. return day1, ndays
  88. def monthcalendar(year, month):
  89. """Return a matrix representing a month's calendar.
  90. Each row represents a week; days outside this month are zero."""
  91. day1, ndays = monthrange(year, month)
  92. rows = []
  93. r7 = range(7)
  94. day = (_firstweekday - day1 + 6) % 7 - 5 # for leading 0's in first week
  95. while day <= ndays:
  96. row = [0, 0, 0, 0, 0, 0, 0]
  97. for i in r7:
  98. if 1 <= day <= ndays: row[i] = day
  99. day = day + 1
  100. rows.append(row)
  101. return rows
  102. def prweek(theweek, width):
  103. """Print a single week (no newline)."""
  104. print week(theweek, width),
  105. def week(theweek, width):
  106. """Returns a single week in a string (no newline)."""
  107. days = []
  108. for day in theweek:
  109. if day == 0:
  110. s = ''
  111. else:
  112. s = '%2i' % day # right-align single-digit days
  113. days.append(s.center(width))
  114. return ' '.join(days)
  115. def weekheader(width):
  116. """Return a header for a week."""
  117. if width >= 9:
  118. names = day_name
  119. else:
  120. names = day_abbr
  121. days = []
  122. for i in range(_firstweekday, _firstweekday + 7):
  123. days.append(names[i%7][:width].center(width))
  124. return ' '.join(days)
  125. def prmonth(theyear, themonth, w=0, l=0):
  126. """Print a month's calendar."""
  127. print month(theyear, themonth, w, l),
  128. def month(theyear, themonth, w=0, l=0):
  129. """Return a month's calendar string (multi-line)."""
  130. w = max(2, w)
  131. l = max(1, l)
  132. s = ("%s %r" % (month_name[themonth], theyear)).center(
  133. 7 * (w + 1) - 1).rstrip() + \
  134. '\n' * l + weekheader(w).rstrip() + '\n' * l
  135. for aweek in monthcalendar(theyear, themonth):
  136. s = s + week(aweek, w).rstrip() + '\n' * l
  137. return s[:-l] + '\n'
  138. # Spacing of month columns for 3-column year calendar
  139. _colwidth = 7*3 - 1 # Amount printed by prweek()
  140. _spacing = 6 # Number of spaces between columns
  141. def format3c(a, b, c, colwidth=_colwidth, spacing=_spacing):
  142. """Prints 3-column formatting for year calendars"""
  143. print format3cstring(a, b, c, colwidth, spacing)
  144. def format3cstring(a, b, c, colwidth=_colwidth, spacing=_spacing):
  145. """Returns a string formatted from 3 strings, centered within 3 columns."""
  146. return (a.center(colwidth) + ' ' * spacing + b.center(colwidth) +
  147. ' ' * spacing + c.center(colwidth))
  148. def prcal(year, w=0, l=0, c=_spacing):
  149. """Print a year's calendar."""
  150. print calendar(year, w, l, c),
  151. def calendar(year, w=0, l=0, c=_spacing):
  152. """Returns a year's calendar as a multi-line string."""
  153. w = max(2, w)
  154. l = max(1, l)
  155. c = max(2, c)
  156. colwidth = (w + 1) * 7 - 1
  157. s = repr(year).center(colwidth * 3 + c * 2).rstrip() + '\n' * l
  158. header = weekheader(w)
  159. header = format3cstring(header, header, header, colwidth, c).rstrip()
  160. for q in range(January, January+12, 3):
  161. s = (s + '\n' * l +
  162. format3cstring(month_name[q], month_name[q+1], month_name[q+2],
  163. colwidth, c).rstrip() +
  164. '\n' * l + header + '\n' * l)
  165. data = []
  166. height = 0
  167. for amonth in range(q, q + 3):
  168. cal = monthcalendar(year, amonth)
  169. if len(cal) > height:
  170. height = len(cal)
  171. data.append(cal)
  172. for i in range(height):
  173. weeks = []
  174. for cal in data:
  175. if i >= len(cal):
  176. weeks.append('')
  177. else:
  178. weeks.append(week(cal[i], w))
  179. s = s + format3cstring(weeks[0], weeks[1], weeks[2],
  180. colwidth, c).rstrip() + '\n' * l
  181. return s[:-l] + '\n'
  182. EPOCH = 1970
  183. _EPOCH_ORD = datetime.date(EPOCH, 1, 1).toordinal()
  184. def timegm(tuple):
  185. """Unrelated but handy function to calculate Unix timestamp from GMT."""
  186. year, month, day, hour, minute, second = tuple[:6]
  187. days = datetime.date(year, month, 1).toordinal() - _EPOCH_ORD + day - 1
  188. hours = days*24 + hour
  189. minutes = hours*60 + minute
  190. seconds = minutes*60 + second
  191. return seconds