# (c) Chui Tey 2007 # http://www.cognoware.com # zellers formula month_rel = { 1 : 0, 2 : 3, 3 : 3, 4 : 6, 5 : 1, 6 : 4, 7 : 6, 8 : 2, 9 : 5, 10 : 0, 11 : 3, 12 : 5, } # TODO: use localized days as in calendar.py # to get days of week and month names dow_text = { 0 : 'Su', 1 : 'Mo', 2 : 'Tu', 3 : 'We', 4 : 'Th', 5 : 'Fr', 6 : 'Sa', } mon_text = { 1 : 'Jan', 2 : 'Feb', 3 : 'Mar', 4 : 'Apr', 5 : 'May', 6 : 'Jun', 7 : 'Jul', 8 : 'Aug', 9 : 'Sep', 10 : 'Oct', 11 : 'Nov', 12 : 'Dec', } def is_leap(year): if divmod(year, 400)[1] == 0: return 1 elif divmod(year, 100)[1] == 0: return 0 elif divmod(year, 4)[1] == 0: return 1 else: return 0 def dayofweek(year, month, day): if month in (1,2) and is_leap(year): mod, rem = divmod(year + year / 4 + month_rel[month] + day - 1 - 2, 7) else: mod, rem = divmod(year + year / 4 + month_rel[month] + day - 0 - 2, 7) return rem # print dayofweek(2006, 02, 15) def dategrid(cols, rows): def date(i, j): d = i+j*cols+1 if d <= 31: return '%2d' % d else: return ' ' assert divmod(cols, 7)[1] == 0 for j in range(rows): #line = " ".join(["%2d" % (divmod(i+j*cols, 31)[1]+1) for i in range(cols)]) line = " ".join([date(i,j) for i in range(cols)]) print "%12s %s" % ("", line) def weekhead(year, cols): headers = {} for month in range(1, 13): dow = dayofweek(year, month, 1) line = " ".join(["%2s" % dow_text[divmod(dow+day,7)[1]] for day in range(cols)]) if not headers.has_key(line): headers[line] = [] headers[line].append(mon_text[month]) for line, months in headers.items(): month_head = " ".join(months) print "%12s %s %-12s" % (month_head, line, month_head) def weekhead2(year1, year2, cols): headers = {} for year in [year1, year2]: for month in range(1, 13): dow = dayofweek(year, month, 1) line = " ".join(["%2s" % dow_text[divmod(dow+day,7)[1]] for day in range(cols)]) dow_key = (dow, line) # used for decorated sort of the week headers if not headers.has_key(dow_key): headers[dow_key] = [] headers[dow_key].append((year, mon_text[month])) weekdays = headers.keys() weekdays.sort() for (dow, line) in weekdays: yearmonths = headers[(dow, line)] month_head1 = " ".join([month for (year, month) in yearmonths if year == year1]) month_head2 = " ".join([month for (year, month) in yearmonths if year == year2]) print "%12s %s %-12s" % (month_head1, line, month_head2) def pryear(year): dategrid(cols, rows) weekhead(year, cols) def pryear2(year1, year2): dategrid(cols, rows) print "%12s %20s %-12s" % (year1, '', year2) weekhead2(year1, year2, cols) # Usage: cols, rows = 7, 5 #pryear(2008) pryear2(2008, 2009)