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