home *** CD-ROM | disk | FTP | other *** search
/ PC World 2002 May / PCWorld_2002-05_cd.bin / Software / TemaCD / activepython / ActivePython-2.1.1.msi / Python21_Lib_calendar.py < prev    next >
Encoding:
Python Source  |  2001-07-26  |  7.3 KB  |  210 lines

  1. """Calendar printing functions
  2.  
  3. Note when comparing these calendars to the ones printed by cal(1): By
  4. default, these calendars have Monday as the first day of the week, and
  5. Sunday as the last (the European convention). Use setfirstweekday() to
  6. set the first day of the week (0=Monday, 6=Sunday)."""
  7.  
  8. # Revision 2: uses functions from built-in time module
  9.  
  10. # Import functions and variables from time module
  11. from time import localtime, mktime
  12.  
  13. __all__ = ["error","setfirstweekday","firstweekday","isleap",
  14.            "leapdays","weekday","monthrange","monthcalendar",
  15.            "prmonth","month","prcal","calendar","timegm"]
  16.  
  17. # Exception raised for bad input (with string parameter for details)
  18. error = ValueError
  19.  
  20. # Constants for months referenced later
  21. January = 1
  22. February = 2
  23.  
  24. # Number of days per month (except for February in leap years)
  25. mdays = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
  26.  
  27. # Full and abbreviated names of weekdays
  28. day_name = ['Monday', 'Tuesday', 'Wednesday', 'Thursday',
  29.             'Friday', 'Saturday', 'Sunday']
  30. day_abbr = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
  31.  
  32. # Full and abbreviated names of months (1-based arrays!!!)
  33. month_name = ['', 'January', 'February', 'March', 'April',
  34.               'May', 'June', 'July', 'August',
  35.               'September', 'October',  'November', 'December']
  36. month_abbr = ['   ', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
  37.               'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
  38.  
  39. # Constants for weekdays
  40. (MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY) = range(7)
  41.  
  42. _firstweekday = 0                       # 0 = Monday, 6 = Sunday
  43.  
  44. def firstweekday():
  45.     return _firstweekday
  46.  
  47. def setfirstweekday(weekday):
  48.     """Set weekday (Monday=0, Sunday=6) to start each week."""
  49.     global _firstweekday
  50.     if not MONDAY <= weekday <= SUNDAY:
  51.         raise ValueError, \
  52.               'bad weekday number; must be 0 (Monday) to 6 (Sunday)'
  53.     _firstweekday = weekday
  54.  
  55. def isleap(year):
  56.     """Return 1 for leap years, 0 for non-leap years."""
  57.     return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
  58.  
  59. def leapdays(y1, y2):
  60.     """Return number of leap years in range [y1, y2).
  61.        Assume y1 <= y2."""
  62.     y1 -= 1
  63.     y2 -= 1
  64.     return (y2/4 - y1/4) - (y2/100 - y1/100) + (y2/400 - y1/400)
  65.  
  66. def weekday(year, month, day):
  67.     """Return weekday (0-6 ~ Mon-Sun) for year (1970-...), month (1-12),
  68.        day (1-31)."""
  69.     secs = mktime((year, month, day, 0, 0, 0, 0, 0, 0))
  70.     tuple = localtime(secs)
  71.     return tuple[6]
  72.  
  73. def monthrange(year, month):
  74.     """Return weekday (0-6 ~ Mon-Sun) and number of days (28-31) for
  75.        year, month."""
  76.     if not 1 <= month <= 12:
  77.         raise ValueError, 'bad month number'
  78.     day1 = weekday(year, month, 1)
  79.     ndays = mdays[month] + (month == February and isleap(year))
  80.     return day1, ndays
  81.  
  82. def monthcalendar(year, month):
  83.     """Return a matrix representing a month's calendar.
  84.        Each row represents a week; days outside this month are zero."""
  85.     day1, ndays = monthrange(year, month)
  86.     rows = []
  87.     r7 = range(7)
  88.     day = (_firstweekday - day1 + 6) % 7 - 5   # for leading 0's in first week
  89.     while day <= ndays:
  90.         row = [0, 0, 0, 0, 0, 0, 0]
  91.         for i in r7:
  92.             if 1 <= day <= ndays: row[i] = day
  93.             day = day + 1
  94.         rows.append(row)
  95.     return rows
  96.  
  97. def _center(str, width):
  98.     """Center a string in a field."""
  99.     n = width - len(str)
  100.     if n <= 0:
  101.         return str
  102.     return ' '*((n+1)/2) + str + ' '*((n)/2)
  103.  
  104. def prweek(theweek, width):
  105.     """Print a single week (no newline)."""
  106.     print week(theweek, width),
  107.  
  108. def week(theweek, width):
  109.     """Returns a single week in a string (no newline)."""
  110.     days = []
  111.     for day in theweek:
  112.         if day == 0:
  113.             s = ''
  114.         else:
  115.             s = '%2i' % day             # right-align single-digit days
  116.         days.append(_center(s, width))
  117.     return ' '.join(days)
  118.  
  119. def weekheader(width):
  120.     """Return a header for a week."""
  121.     if width >= 9:
  122.         names = day_name
  123.     else:
  124.         names = day_abbr
  125.     days = []
  126.     for i in range(_firstweekday, _firstweekday + 7):
  127.         days.append(_center(names[i%7][:width], width))
  128.     return ' '.join(days)
  129.  
  130. def prmonth(theyear, themonth, w=0, l=0):
  131.     """Print a month's calendar."""
  132.     print month(theyear, themonth, w, l),
  133.  
  134. def month(theyear, themonth, w=0, l=0):
  135.     """Return a month's calendar string (multi-line)."""
  136.     w = max(2, w)
  137.     l = max(1, l)
  138.     s = (_center(month_name[themonth] + ' ' + `theyear`,
  139.                  7 * (w + 1) - 1).rstrip() +
  140.          '\n' * l + weekheader(w).rstrip() + '\n' * l)
  141.     for aweek in monthcalendar(theyear, themonth):
  142.         s = s + week(aweek, w).rstrip() + '\n' * l
  143.     return s[:-l] + '\n'
  144.  
  145. # Spacing of month columns for 3-column year calendar
  146. _colwidth = 7*3 - 1         # Amount printed by prweek()
  147. _spacing = 6                # Number of spaces between columns
  148.  
  149. def format3c(a, b, c, colwidth=_colwidth, spacing=_spacing):
  150.     """Prints 3-column formatting for year calendars"""
  151.     print format3cstring(a, b, c, colwidth, spacing)
  152.  
  153. def format3cstring(a, b, c, colwidth=_colwidth, spacing=_spacing):
  154.     """Returns a string formatted from 3 strings, centered within 3 columns."""
  155.     return (_center(a, colwidth) + ' ' * spacing + _center(b, colwidth) +
  156.             ' ' * spacing + _center(c, colwidth))
  157.  
  158. def prcal(year, w=0, l=0, c=_spacing):
  159.     """Print a year's calendar."""
  160.     print calendar(year, w, l, c),
  161.  
  162. def calendar(year, w=0, l=0, c=_spacing):
  163.     """Returns a year's calendar as a multi-line string."""
  164.     w = max(2, w)
  165.     l = max(1, l)
  166.     c = max(2, c)
  167.     colwidth = (w + 1) * 7 - 1
  168.     s = _center(`year`, colwidth * 3 + c * 2).rstrip() + '\n' * l
  169.     header = weekheader(w)
  170.     header = format3cstring(header, header, header, colwidth, c).rstrip()
  171.     for q in range(January, January+12, 3):
  172.         s = (s + '\n' * l +
  173.              format3cstring(month_name[q], month_name[q+1], month_name[q+2],
  174.                             colwidth, c).rstrip() +
  175.              '\n' * l + header + '\n' * l)
  176.         data = []
  177.         height = 0
  178.         for amonth in range(q, q + 3):
  179.             cal = monthcalendar(year, amonth)
  180.             if len(cal) > height:
  181.                 height = len(cal)
  182.             data.append(cal)
  183.         for i in range(height):
  184.             weeks = []
  185.             for cal in data:
  186.                 if i >= len(cal):
  187.                     weeks.append('')
  188.                 else:
  189.                     weeks.append(week(cal[i], w))
  190.             s = s + format3cstring(weeks[0], weeks[1], weeks[2],
  191.                                    colwidth, c).rstrip() + '\n' * l
  192.     return s[:-l] + '\n'
  193.  
  194. EPOCH = 1970
  195. def timegm(tuple):
  196.     """Unrelated but handy function to calculate Unix timestamp from GMT."""
  197.     year, month, day, hour, minute, second = tuple[:6]
  198.     assert year >= EPOCH
  199.     assert 1 <= month <= 12
  200.     days = 365*(year-EPOCH) + leapdays(EPOCH, year)
  201.     for i in range(1, month):
  202.         days = days + mdays[i]
  203.     if month > 2 and isleap(year):
  204.         days = days + 1
  205.     days = days + day - 1
  206.     hours = days*24 + hour
  207.     minutes = hours*60 + minute
  208.     seconds = minutes*60 + second
  209.     return seconds
  210.