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