1 #!/usr/bin/env python 2 3 import libxml2dom 4 import calendar 5 6 # Borrowed from calendar, but with a non-global first weekday variable. 7 8 def monthcalendar(year, month, firstweekday=0): 9 """Return a matrix representing a month's calendar. 10 Each row represents a week; days outside this month are zero.""" 11 day1, ndays = calendar.monthrange(year, month) 12 rows = [] 13 r7 = range(7) 14 day = (firstweekday - day1 + 6) % 7 - 5 # for leading 0's in first week 15 while day <= ndays: 16 row = [0, 0, 0, 0, 0, 0, 0] 17 for i in r7: 18 if 1 <= day <= ndays: row[i] = day 19 day = day + 1 20 rows.append(row) 21 return rows 22 23 # XML production functions. 24 25 def write_month_to_document(doc, root, year, month): 26 weeks = monthcalendar(year, month) 27 month_element = root.appendChild(doc.createElement("month")) 28 month_element.setAttribute("number", str(month)) 29 month_element.setAttribute("year", str(year)) 30 for numbers in weeks: 31 week_element = month_element.appendChild(doc.createElement("week")) 32 for number in numbers: 33 day_element = week_element.appendChild(doc.createElement("day")) 34 if number != 0: 35 day_element.setAttribute("date", "%04d%02d%02d" % (year, month, number)) 36 day_element.setAttribute("number", str(number)) 37 38 def get_calendar_for_month(year, month): 39 doc = libxml2dom.createDocument(None, "calendar", None) 40 write_month_to_document(doc, doc.childNodes[-1], year, month) 41 return doc 42 43 if __name__ == "__main__": 44 import sys 45 try: 46 print get_calendar_for_month(int(sys.argv[1]), int(sys.argv[2])).toString() 47 except (IndexError, ValueError): 48 print "Please specify a year and a month (numeric, 1-12)." 49 50 # vim: tabstop=4 expandtab shiftwidth=4