Skip Montanaro | ad3bc44 | 2000-08-30 14:01:28 +0000 | [diff] [blame] | 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).""" |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 7 | |
Christian Heimes | 96f3163 | 2007-11-12 01:32:03 +0000 | [diff] [blame] | 8 | import sys |
| 9 | import datetime |
| 10 | import locale as _locale |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 11 | |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 12 | __all__ = ["IllegalMonthError", "IllegalWeekdayError", "setfirstweekday", |
| 13 | "firstweekday", "isleap", "leapdays", "weekday", "monthrange", |
| 14 | "monthcalendar", "prmonth", "month", "prcal", "calendar", |
| 15 | "timegm", "month_name", "month_abbr", "day_name", "day_abbr"] |
Skip Montanaro | e99d5ea | 2001-01-20 19:54:20 +0000 | [diff] [blame] | 16 | |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 17 | # Exception raised for bad input (with string parameter for details) |
Guido van Rossum | 00245cf | 1999-05-03 18:07:40 +0000 | [diff] [blame] | 18 | error = ValueError |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 19 | |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 20 | # Exceptions raised for bad input |
| 21 | class IllegalMonthError(ValueError): |
| 22 | def __init__(self, month): |
| 23 | self.month = month |
| 24 | def __str__(self): |
| 25 | return "bad month number %r; must be 1-12" % self.month |
| 26 | |
| 27 | |
| 28 | class IllegalWeekdayError(ValueError): |
| 29 | def __init__(self, weekday): |
| 30 | self.weekday = weekday |
| 31 | def __str__(self): |
| 32 | return "bad weekday number %r; must be 0 (Monday) to 6 (Sunday)" % self.weekday |
| 33 | |
| 34 | |
Guido van Rossum | 9b3bc71 | 1993-06-20 21:02:22 +0000 | [diff] [blame] | 35 | # Constants for months referenced later |
| 36 | January = 1 |
| 37 | February = 2 |
| 38 | |
| 39 | # Number of days per month (except for February in leap years) |
| 40 | mdays = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] |
| 41 | |
Tim Peters | 0c2c8e7 | 2002-03-23 03:26:53 +0000 | [diff] [blame] | 42 | # This module used to have hard-coded lists of day and month names, as |
| 43 | # English strings. The classes following emulate a read-only version of |
| 44 | # that, but supply localized names. Note that the values are computed |
| 45 | # fresh on each call, in case the user changes locale between calls. |
| 46 | |
Raymond Hettinger | 9c051d7 | 2002-06-20 03:38:12 +0000 | [diff] [blame] | 47 | class _localized_month: |
Tim Peters | bbc0d44 | 2004-11-13 16:18:32 +0000 | [diff] [blame] | 48 | |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 49 | _months = [datetime.date(2001, i+1, 1).strftime for i in range(12)] |
Tim Peters | bbc0d44 | 2004-11-13 16:18:32 +0000 | [diff] [blame] | 50 | _months.insert(0, lambda x: "") |
| 51 | |
Tim Peters | 0c2c8e7 | 2002-03-23 03:26:53 +0000 | [diff] [blame] | 52 | def __init__(self, format): |
Barry Warsaw | 1d09910 | 2001-05-22 15:58:30 +0000 | [diff] [blame] | 53 | self.format = format |
Tim Peters | 0c2c8e7 | 2002-03-23 03:26:53 +0000 | [diff] [blame] | 54 | |
| 55 | def __getitem__(self, i): |
Tim Peters | bbc0d44 | 2004-11-13 16:18:32 +0000 | [diff] [blame] | 56 | funcs = self._months[i] |
| 57 | if isinstance(i, slice): |
| 58 | return [f(self.format) for f in funcs] |
| 59 | else: |
| 60 | return funcs(self.format) |
Tim Peters | 0c2c8e7 | 2002-03-23 03:26:53 +0000 | [diff] [blame] | 61 | |
Skip Montanaro | 4c83495 | 2002-03-15 04:08:38 +0000 | [diff] [blame] | 62 | def __len__(self): |
Tim Peters | 0c2c8e7 | 2002-03-23 03:26:53 +0000 | [diff] [blame] | 63 | return 13 |
| 64 | |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 65 | |
Raymond Hettinger | 9c051d7 | 2002-06-20 03:38:12 +0000 | [diff] [blame] | 66 | class _localized_day: |
Tim Peters | bbc0d44 | 2004-11-13 16:18:32 +0000 | [diff] [blame] | 67 | |
| 68 | # January 1, 2001, was a Monday. |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 69 | _days = [datetime.date(2001, 1, i+1).strftime for i in range(7)] |
Tim Peters | bbc0d44 | 2004-11-13 16:18:32 +0000 | [diff] [blame] | 70 | |
Tim Peters | 0c2c8e7 | 2002-03-23 03:26:53 +0000 | [diff] [blame] | 71 | def __init__(self, format): |
| 72 | self.format = format |
| 73 | |
| 74 | def __getitem__(self, i): |
Tim Peters | bbc0d44 | 2004-11-13 16:18:32 +0000 | [diff] [blame] | 75 | funcs = self._days[i] |
| 76 | if isinstance(i, slice): |
| 77 | return [f(self.format) for f in funcs] |
| 78 | else: |
| 79 | return funcs(self.format) |
Tim Peters | 0c2c8e7 | 2002-03-23 03:26:53 +0000 | [diff] [blame] | 80 | |
Neal Norwitz | 492faa5 | 2004-06-07 03:47:06 +0000 | [diff] [blame] | 81 | def __len__(self): |
Tim Peters | 0c2c8e7 | 2002-03-23 03:26:53 +0000 | [diff] [blame] | 82 | return 7 |
Barry Warsaw | 1d09910 | 2001-05-22 15:58:30 +0000 | [diff] [blame] | 83 | |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 84 | |
Guido van Rossum | 9b3bc71 | 1993-06-20 21:02:22 +0000 | [diff] [blame] | 85 | # Full and abbreviated names of weekdays |
Tim Peters | 0c2c8e7 | 2002-03-23 03:26:53 +0000 | [diff] [blame] | 86 | day_name = _localized_day('%A') |
| 87 | day_abbr = _localized_day('%a') |
Guido van Rossum | 9b3bc71 | 1993-06-20 21:02:22 +0000 | [diff] [blame] | 88 | |
Guido van Rossum | 5cfa5df | 1993-06-23 09:30:50 +0000 | [diff] [blame] | 89 | # Full and abbreviated names of months (1-based arrays!!!) |
Tim Peters | 0c2c8e7 | 2002-03-23 03:26:53 +0000 | [diff] [blame] | 90 | month_name = _localized_month('%B') |
| 91 | month_abbr = _localized_month('%b') |
Guido van Rossum | 9b3bc71 | 1993-06-20 21:02:22 +0000 | [diff] [blame] | 92 | |
Skip Montanaro | ad3bc44 | 2000-08-30 14:01:28 +0000 | [diff] [blame] | 93 | # Constants for weekdays |
| 94 | (MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY) = range(7) |
| 95 | |
Skip Montanaro | ad3bc44 | 2000-08-30 14:01:28 +0000 | [diff] [blame] | 96 | |
Guido van Rossum | 9b3bc71 | 1993-06-20 21:02:22 +0000 | [diff] [blame] | 97 | def isleap(year): |
Alexander Belopolsky | f87cc04 | 2010-10-19 17:43:50 +0000 | [diff] [blame] | 98 | """Return True for leap years, False for non-leap years.""" |
Fred Drake | 8152d32 | 2000-12-12 23:20:45 +0000 | [diff] [blame] | 99 | return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) |
Guido van Rossum | 9b3bc71 | 1993-06-20 21:02:22 +0000 | [diff] [blame] | 100 | |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 101 | |
Guido van Rossum | 9b3bc71 | 1993-06-20 21:02:22 +0000 | [diff] [blame] | 102 | def leapdays(y1, y2): |
Guido van Rossum | 4acc25b | 2000-02-02 15:10:15 +0000 | [diff] [blame] | 103 | """Return number of leap years in range [y1, y2). |
Guido van Rossum | 46735ad | 2000-10-09 12:42:04 +0000 | [diff] [blame] | 104 | Assume y1 <= y2.""" |
| 105 | y1 -= 1 |
| 106 | y2 -= 1 |
Raymond Hettinger | e11b510 | 2002-12-25 16:37:19 +0000 | [diff] [blame] | 107 | return (y2//4 - y1//4) - (y2//100 - y1//100) + (y2//400 - y1//400) |
Guido van Rossum | 9b3bc71 | 1993-06-20 21:02:22 +0000 | [diff] [blame] | 108 | |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 109 | |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 110 | def weekday(year, month, day): |
Skip Montanaro | ad3bc44 | 2000-08-30 14:01:28 +0000 | [diff] [blame] | 111 | """Return weekday (0-6 ~ Mon-Sun) for year (1970-...), month (1-12), |
| 112 | day (1-31).""" |
Raymond Hettinger | e11b510 | 2002-12-25 16:37:19 +0000 | [diff] [blame] | 113 | return datetime.date(year, month, day).weekday() |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 114 | |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 115 | |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 116 | def monthrange(year, month): |
Skip Montanaro | ad3bc44 | 2000-08-30 14:01:28 +0000 | [diff] [blame] | 117 | """Return weekday (0-6 ~ Mon-Sun) and number of days (28-31) for |
| 118 | year, month.""" |
| 119 | if not 1 <= month <= 12: |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 120 | raise IllegalMonthError(month) |
Guido van Rossum | 4acc25b | 2000-02-02 15:10:15 +0000 | [diff] [blame] | 121 | day1 = weekday(year, month, 1) |
| 122 | ndays = mdays[month] + (month == February and isleap(year)) |
| 123 | return day1, ndays |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 124 | |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 125 | |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 126 | class Calendar(object): |
| 127 | """ |
| 128 | Base calendar class. This class doesn't do any formatting. It simply |
| 129 | provides data to subclasses. |
| 130 | """ |
Skip Montanaro | ad3bc44 | 2000-08-30 14:01:28 +0000 | [diff] [blame] | 131 | |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 132 | def __init__(self, firstweekday=0): |
| 133 | self.firstweekday = firstweekday # 0 = Monday, 6 = Sunday |
| 134 | |
| 135 | def getfirstweekday(self): |
| 136 | return self._firstweekday % 7 |
| 137 | |
| 138 | def setfirstweekday(self, firstweekday): |
| 139 | self._firstweekday = firstweekday |
| 140 | |
| 141 | firstweekday = property(getfirstweekday, setfirstweekday) |
| 142 | |
| 143 | def iterweekdays(self): |
| 144 | """ |
| 145 | Return a iterator for one week of weekday numbers starting with the |
| 146 | configured first one. |
| 147 | """ |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 148 | for i in range(self.firstweekday, self.firstweekday + 7): |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 149 | yield i%7 |
| 150 | |
| 151 | def itermonthdates(self, year, month): |
| 152 | """ |
| 153 | Return an iterator for one month. The iterator will yield datetime.date |
| 154 | values and will always iterate through complete weeks, so it will yield |
| 155 | dates outside the specified month. |
| 156 | """ |
| 157 | date = datetime.date(year, month, 1) |
| 158 | # Go back to the beginning of the week |
| 159 | days = (date.weekday() - self.firstweekday) % 7 |
| 160 | date -= datetime.timedelta(days=days) |
| 161 | oneday = datetime.timedelta(days=1) |
| 162 | while True: |
| 163 | yield date |
Ezio Melotti | 85710a4 | 2012-09-21 17:26:35 +0300 | [diff] [blame] | 164 | try: |
| 165 | date += oneday |
| 166 | except OverflowError: |
| 167 | # Adding one day could fail after datetime.MAXYEAR |
| 168 | break |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 169 | if date.month != month and date.weekday() == self.firstweekday: |
| 170 | break |
| 171 | |
| 172 | def itermonthdays2(self, year, month): |
| 173 | """ |
| 174 | Like itermonthdates(), but will yield (day number, weekday number) |
| 175 | tuples. For days outside the specified month the day number is 0. |
| 176 | """ |
| 177 | for date in self.itermonthdates(year, month): |
| 178 | if date.month != month: |
| 179 | yield (0, date.weekday()) |
| 180 | else: |
| 181 | yield (date.day, date.weekday()) |
| 182 | |
| 183 | def itermonthdays(self, year, month): |
| 184 | """ |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 185 | Like itermonthdates(), but will yield day numbers. For days outside |
| 186 | the specified month the day number is 0. |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 187 | """ |
| 188 | for date in self.itermonthdates(year, month): |
| 189 | if date.month != month: |
| 190 | yield 0 |
| 191 | else: |
| 192 | yield date.day |
| 193 | |
| 194 | def monthdatescalendar(self, year, month): |
| 195 | """ |
| 196 | Return a matrix (list of lists) representing a month's calendar. |
| 197 | Each row represents a week; week entries are datetime.date values. |
| 198 | """ |
| 199 | dates = list(self.itermonthdates(year, month)) |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 200 | return [ dates[i:i+7] for i in range(0, len(dates), 7) ] |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 201 | |
| 202 | def monthdays2calendar(self, year, month): |
| 203 | """ |
| 204 | Return a matrix representing a month's calendar. |
| 205 | Each row represents a week; week entries are |
| 206 | (day number, weekday number) tuples. Day numbers outside this month |
| 207 | are zero. |
| 208 | """ |
| 209 | days = list(self.itermonthdays2(year, month)) |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 210 | return [ days[i:i+7] for i in range(0, len(days), 7) ] |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 211 | |
| 212 | def monthdayscalendar(self, year, month): |
| 213 | """ |
| 214 | Return a matrix representing a month's calendar. |
| 215 | Each row represents a week; days outside this month are zero. |
| 216 | """ |
| 217 | days = list(self.itermonthdays(year, month)) |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 218 | return [ days[i:i+7] for i in range(0, len(days), 7) ] |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 219 | |
| 220 | def yeardatescalendar(self, year, width=3): |
| 221 | """ |
| 222 | Return the data for the specified year ready for formatting. The return |
Ezio Melotti | 30b9d5d | 2013-08-17 15:50:46 +0300 | [diff] [blame] | 223 | value is a list of month rows. Each month row contains up to width months. |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 224 | Each month contains between 4 and 6 weeks and each week contains 1-7 |
| 225 | days. Days are datetime.date objects. |
| 226 | """ |
| 227 | months = [ |
| 228 | self.monthdatescalendar(year, i) |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 229 | for i in range(January, January+12) |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 230 | ] |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 231 | return [months[i:i+width] for i in range(0, len(months), width) ] |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 232 | |
| 233 | def yeardays2calendar(self, year, width=3): |
| 234 | """ |
| 235 | Return the data for the specified year ready for formatting (similar to |
| 236 | yeardatescalendar()). Entries in the week lists are |
| 237 | (day number, weekday number) tuples. Day numbers outside this month are |
| 238 | zero. |
| 239 | """ |
| 240 | months = [ |
| 241 | self.monthdays2calendar(year, i) |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 242 | for i in range(January, January+12) |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 243 | ] |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 244 | return [months[i:i+width] for i in range(0, len(months), width) ] |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 245 | |
| 246 | def yeardayscalendar(self, year, width=3): |
| 247 | """ |
| 248 | Return the data for the specified year ready for formatting (similar to |
| 249 | yeardatescalendar()). Entries in the week lists are day numbers. |
| 250 | Day numbers outside this month are zero. |
| 251 | """ |
| 252 | months = [ |
| 253 | self.monthdayscalendar(year, i) |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 254 | for i in range(January, January+12) |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 255 | ] |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 256 | return [months[i:i+width] for i in range(0, len(months), width) ] |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 257 | |
| 258 | |
| 259 | class TextCalendar(Calendar): |
| 260 | """ |
| 261 | Subclass of Calendar that outputs a calendar as a simple plain text |
| 262 | similar to the UNIX program cal. |
| 263 | """ |
| 264 | |
| 265 | def prweek(self, theweek, width): |
| 266 | """ |
| 267 | Print a single week (no newline). |
| 268 | """ |
Christian Heimes | 32fbe59 | 2007-11-12 15:01:33 +0000 | [diff] [blame] | 269 | print(self.formatweek(theweek, width), end=' ') |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 270 | |
| 271 | def formatday(self, day, weekday, width): |
| 272 | """ |
| 273 | Returns a formatted day. |
| 274 | """ |
Skip Montanaro | ad3bc44 | 2000-08-30 14:01:28 +0000 | [diff] [blame] | 275 | if day == 0: |
| 276 | s = '' |
| 277 | else: |
| 278 | s = '%2i' % day # right-align single-digit days |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 279 | return s.center(width) |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 280 | |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 281 | def formatweek(self, theweek, width): |
| 282 | """ |
| 283 | Returns a single week in a string (no newline). |
| 284 | """ |
| 285 | return ' '.join(self.formatday(d, wd, width) for (d, wd) in theweek) |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 286 | |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 287 | def formatweekday(self, day, width): |
| 288 | """ |
| 289 | Returns a formatted week day name. |
| 290 | """ |
| 291 | if width >= 9: |
| 292 | names = day_name |
| 293 | else: |
| 294 | names = day_abbr |
| 295 | return names[day][:width].center(width) |
Skip Montanaro | ad3bc44 | 2000-08-30 14:01:28 +0000 | [diff] [blame] | 296 | |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 297 | def formatweekheader(self, width): |
| 298 | """ |
| 299 | Return a header for a week. |
| 300 | """ |
| 301 | return ' '.join(self.formatweekday(i, width) for i in self.iterweekdays()) |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 302 | |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 303 | def formatmonthname(self, theyear, themonth, width, withyear=True): |
| 304 | """ |
| 305 | Return a formatted month name. |
| 306 | """ |
| 307 | s = month_name[themonth] |
| 308 | if withyear: |
| 309 | s = "%s %r" % (s, theyear) |
| 310 | return s.center(width) |
| 311 | |
| 312 | def prmonth(self, theyear, themonth, w=0, l=0): |
| 313 | """ |
| 314 | Print a month's calendar. |
| 315 | """ |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 316 | print(self.formatmonth(theyear, themonth, w, l), end=' ') |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 317 | |
| 318 | def formatmonth(self, theyear, themonth, w=0, l=0): |
| 319 | """ |
| 320 | Return a month's calendar string (multi-line). |
| 321 | """ |
| 322 | w = max(2, w) |
| 323 | l = max(1, l) |
| 324 | s = self.formatmonthname(theyear, themonth, 7 * (w + 1) - 1) |
| 325 | s = s.rstrip() |
| 326 | s += '\n' * l |
| 327 | s += self.formatweekheader(w).rstrip() |
| 328 | s += '\n' * l |
| 329 | for week in self.monthdays2calendar(theyear, themonth): |
| 330 | s += self.formatweek(week, w).rstrip() |
| 331 | s += '\n' * l |
| 332 | return s |
| 333 | |
| 334 | def formatyear(self, theyear, w=2, l=1, c=6, m=3): |
| 335 | """ |
| 336 | Returns a year's calendar as a multi-line string. |
| 337 | """ |
| 338 | w = max(2, w) |
| 339 | l = max(1, l) |
| 340 | c = max(2, c) |
| 341 | colwidth = (w + 1) * 7 - 1 |
| 342 | v = [] |
| 343 | a = v.append |
| 344 | a(repr(theyear).center(colwidth*m+c*(m-1)).rstrip()) |
| 345 | a('\n'*l) |
| 346 | header = self.formatweekheader(w) |
| 347 | for (i, row) in enumerate(self.yeardays2calendar(theyear, m)): |
| 348 | # months in this row |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 349 | months = range(m*i+1, min(m*(i+1)+1, 13)) |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 350 | a('\n'*l) |
| 351 | names = (self.formatmonthname(theyear, k, colwidth, False) |
| 352 | for k in months) |
| 353 | a(formatstring(names, colwidth, c).rstrip()) |
| 354 | a('\n'*l) |
| 355 | headers = (header for k in months) |
| 356 | a(formatstring(headers, colwidth, c).rstrip()) |
| 357 | a('\n'*l) |
| 358 | # max number of weeks for this row |
| 359 | height = max(len(cal) for cal in row) |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 360 | for j in range(height): |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 361 | weeks = [] |
| 362 | for cal in row: |
| 363 | if j >= len(cal): |
| 364 | weeks.append('') |
| 365 | else: |
| 366 | weeks.append(self.formatweek(cal[j], w)) |
| 367 | a(formatstring(weeks, colwidth, c).rstrip()) |
| 368 | a('\n' * l) |
| 369 | return ''.join(v) |
| 370 | |
| 371 | def pryear(self, theyear, w=0, l=0, c=6, m=3): |
| 372 | """Print a year's calendar.""" |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 373 | print(self.formatyear(theyear, w, l, c, m)) |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 374 | |
| 375 | |
| 376 | class HTMLCalendar(Calendar): |
| 377 | """ |
| 378 | This calendar returns complete HTML pages. |
| 379 | """ |
| 380 | |
| 381 | # CSS classes for the day <td>s |
| 382 | cssclasses = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"] |
| 383 | |
| 384 | def formatday(self, day, weekday): |
| 385 | """ |
| 386 | Return a day as a table cell. |
| 387 | """ |
| 388 | if day == 0: |
| 389 | return '<td class="noday"> </td>' # day outside month |
| 390 | else: |
| 391 | return '<td class="%s">%d</td>' % (self.cssclasses[weekday], day) |
| 392 | |
| 393 | def formatweek(self, theweek): |
| 394 | """ |
| 395 | Return a complete week as a table row. |
| 396 | """ |
| 397 | s = ''.join(self.formatday(d, wd) for (d, wd) in theweek) |
| 398 | return '<tr>%s</tr>' % s |
| 399 | |
| 400 | def formatweekday(self, day): |
| 401 | """ |
| 402 | Return a weekday name as a table header. |
| 403 | """ |
| 404 | return '<th class="%s">%s</th>' % (self.cssclasses[day], day_abbr[day]) |
| 405 | |
| 406 | def formatweekheader(self): |
| 407 | """ |
| 408 | Return a header for a week as a table row. |
| 409 | """ |
| 410 | s = ''.join(self.formatweekday(i) for i in self.iterweekdays()) |
| 411 | return '<tr>%s</tr>' % s |
| 412 | |
| 413 | def formatmonthname(self, theyear, themonth, withyear=True): |
| 414 | """ |
| 415 | Return a month name as a table row. |
| 416 | """ |
| 417 | if withyear: |
| 418 | s = '%s %s' % (month_name[themonth], theyear) |
| 419 | else: |
| 420 | s = '%s' % month_name[themonth] |
| 421 | return '<tr><th colspan="7" class="month">%s</th></tr>' % s |
| 422 | |
| 423 | def formatmonth(self, theyear, themonth, withyear=True): |
| 424 | """ |
| 425 | Return a formatted month as a table. |
| 426 | """ |
| 427 | v = [] |
| 428 | a = v.append |
| 429 | a('<table border="0" cellpadding="0" cellspacing="0" class="month">') |
| 430 | a('\n') |
| 431 | a(self.formatmonthname(theyear, themonth, withyear=withyear)) |
| 432 | a('\n') |
| 433 | a(self.formatweekheader()) |
| 434 | a('\n') |
| 435 | for week in self.monthdays2calendar(theyear, themonth): |
| 436 | a(self.formatweek(week)) |
| 437 | a('\n') |
| 438 | a('</table>') |
| 439 | a('\n') |
| 440 | return ''.join(v) |
| 441 | |
| 442 | def formatyear(self, theyear, width=3): |
| 443 | """ |
| 444 | Return a formatted year as a table of tables. |
| 445 | """ |
| 446 | v = [] |
| 447 | a = v.append |
| 448 | width = max(width, 1) |
| 449 | a('<table border="0" cellpadding="0" cellspacing="0" class="year">') |
| 450 | a('\n') |
| 451 | a('<tr><th colspan="%d" class="year">%s</th></tr>' % (width, theyear)) |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 452 | for i in range(January, January+12, width): |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 453 | # months in this row |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 454 | months = range(i, min(i+width, 13)) |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 455 | a('<tr>') |
| 456 | for m in months: |
| 457 | a('<td>') |
| 458 | a(self.formatmonth(theyear, m, withyear=False)) |
| 459 | a('</td>') |
| 460 | a('</tr>') |
| 461 | a('</table>') |
| 462 | return ''.join(v) |
| 463 | |
| 464 | def formatyearpage(self, theyear, width=3, css='calendar.css', encoding=None): |
| 465 | """ |
| 466 | Return a formatted year as a complete HTML page. |
| 467 | """ |
| 468 | if encoding is None: |
| 469 | encoding = sys.getdefaultencoding() |
| 470 | v = [] |
| 471 | a = v.append |
| 472 | a('<?xml version="1.0" encoding="%s"?>\n' % encoding) |
| 473 | a('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n') |
| 474 | a('<html>\n') |
| 475 | a('<head>\n') |
| 476 | a('<meta http-equiv="Content-Type" content="text/html; charset=%s" />\n' % encoding) |
| 477 | if css is not None: |
| 478 | a('<link rel="stylesheet" type="text/css" href="%s" />\n' % css) |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 479 | a('<title>Calendar for %d</title>\n' % theyear) |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 480 | a('</head>\n') |
| 481 | a('<body>\n') |
| 482 | a(self.formatyear(theyear, width)) |
| 483 | a('</body>\n') |
| 484 | a('</html>\n') |
| 485 | return ''.join(v).encode(encoding, "xmlcharrefreplace") |
| 486 | |
| 487 | |
Georg Brandl | fd68087 | 2008-06-08 08:40:05 +0000 | [diff] [blame] | 488 | class different_locale: |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 489 | def __init__(self, locale): |
| 490 | self.locale = locale |
| 491 | |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 492 | def __enter__(self): |
Georg Brandl | 7004bd1 | 2010-10-19 18:54:25 +0000 | [diff] [blame] | 493 | self.oldlocale = _locale.getlocale(_locale.LC_TIME) |
| 494 | _locale.setlocale(_locale.LC_TIME, self.locale) |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 495 | |
| 496 | def __exit__(self, *args): |
Christian Heimes | 96f3163 | 2007-11-12 01:32:03 +0000 | [diff] [blame] | 497 | _locale.setlocale(_locale.LC_TIME, self.oldlocale) |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 498 | |
| 499 | |
| 500 | class LocaleTextCalendar(TextCalendar): |
| 501 | """ |
| 502 | This class can be passed a locale name in the constructor and will return |
| 503 | month and weekday names in the specified locale. If this locale includes |
| 504 | an encoding all strings containing month and weekday names will be returned |
| 505 | as unicode. |
| 506 | """ |
| 507 | |
| 508 | def __init__(self, firstweekday=0, locale=None): |
| 509 | TextCalendar.__init__(self, firstweekday) |
| 510 | if locale is None: |
Christian Heimes | 96f3163 | 2007-11-12 01:32:03 +0000 | [diff] [blame] | 511 | locale = _locale.getdefaultlocale() |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 512 | self.locale = locale |
| 513 | |
| 514 | def formatweekday(self, day, width): |
Georg Brandl | fd68087 | 2008-06-08 08:40:05 +0000 | [diff] [blame] | 515 | with different_locale(self.locale): |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 516 | if width >= 9: |
| 517 | names = day_name |
| 518 | else: |
| 519 | names = day_abbr |
| 520 | name = names[day] |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 521 | return name[:width].center(width) |
| 522 | |
| 523 | def formatmonthname(self, theyear, themonth, width, withyear=True): |
Georg Brandl | fd68087 | 2008-06-08 08:40:05 +0000 | [diff] [blame] | 524 | with different_locale(self.locale): |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 525 | s = month_name[themonth] |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 526 | if withyear: |
| 527 | s = "%s %r" % (s, theyear) |
| 528 | return s.center(width) |
| 529 | |
| 530 | |
| 531 | class LocaleHTMLCalendar(HTMLCalendar): |
| 532 | """ |
| 533 | This class can be passed a locale name in the constructor and will return |
| 534 | month and weekday names in the specified locale. If this locale includes |
| 535 | an encoding all strings containing month and weekday names will be returned |
| 536 | as unicode. |
| 537 | """ |
| 538 | def __init__(self, firstweekday=0, locale=None): |
| 539 | HTMLCalendar.__init__(self, firstweekday) |
| 540 | if locale is None: |
Christian Heimes | 96f3163 | 2007-11-12 01:32:03 +0000 | [diff] [blame] | 541 | locale = _locale.getdefaultlocale() |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 542 | self.locale = locale |
| 543 | |
| 544 | def formatweekday(self, day): |
Georg Brandl | fd68087 | 2008-06-08 08:40:05 +0000 | [diff] [blame] | 545 | with different_locale(self.locale): |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 546 | s = day_abbr[day] |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 547 | return '<th class="%s">%s</th>' % (self.cssclasses[day], s) |
| 548 | |
| 549 | def formatmonthname(self, theyear, themonth, withyear=True): |
Georg Brandl | fd68087 | 2008-06-08 08:40:05 +0000 | [diff] [blame] | 550 | with different_locale(self.locale): |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 551 | s = month_name[themonth] |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 552 | if withyear: |
| 553 | s = '%s %s' % (s, theyear) |
| 554 | return '<tr><th colspan="7" class="month">%s</th></tr>' % s |
| 555 | |
| 556 | |
| 557 | # Support for old module level interface |
| 558 | c = TextCalendar() |
| 559 | |
| 560 | firstweekday = c.getfirstweekday |
| 561 | |
| 562 | def setfirstweekday(firstweekday): |
| 563 | if not MONDAY <= firstweekday <= SUNDAY: |
| 564 | raise IllegalWeekdayError(firstweekday) |
| 565 | c.firstweekday = firstweekday |
| 566 | |
| 567 | monthcalendar = c.monthdayscalendar |
| 568 | prweek = c.prweek |
| 569 | week = c.formatweek |
| 570 | weekheader = c.formatweekheader |
| 571 | prmonth = c.prmonth |
| 572 | month = c.formatmonth |
| 573 | calendar = c.formatyear |
| 574 | prcal = c.pryear |
| 575 | |
| 576 | |
| 577 | # Spacing of month columns for multi-column year calendar |
Guido van Rossum | 4acc25b | 2000-02-02 15:10:15 +0000 | [diff] [blame] | 578 | _colwidth = 7*3 - 1 # Amount printed by prweek() |
Skip Montanaro | ad3bc44 | 2000-08-30 14:01:28 +0000 | [diff] [blame] | 579 | _spacing = 6 # Number of spaces between columns |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 580 | |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 581 | |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 582 | def format(cols, colwidth=_colwidth, spacing=_spacing): |
| 583 | """Prints multi-column formatting for year calendars""" |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 584 | print(formatstring(cols, colwidth, spacing)) |
Skip Montanaro | ad3bc44 | 2000-08-30 14:01:28 +0000 | [diff] [blame] | 585 | |
Skip Montanaro | ad3bc44 | 2000-08-30 14:01:28 +0000 | [diff] [blame] | 586 | |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 587 | def formatstring(cols, colwidth=_colwidth, spacing=_spacing): |
| 588 | """Returns a string formatted from n strings, centered within n columns.""" |
| 589 | spacing *= ' ' |
| 590 | return spacing.join(c.center(colwidth) for c in cols) |
| 591 | |
Guido van Rossum | b39aff8 | 1999-06-09 15:07:38 +0000 | [diff] [blame] | 592 | |
Guido van Rossum | b39aff8 | 1999-06-09 15:07:38 +0000 | [diff] [blame] | 593 | EPOCH = 1970 |
Alexander Belopolsky | 97958cf | 2010-06-14 18:33:19 +0000 | [diff] [blame] | 594 | _EPOCH_ORD = datetime.date(EPOCH, 1, 1).toordinal() |
| 595 | |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 596 | |
Guido van Rossum | b39aff8 | 1999-06-09 15:07:38 +0000 | [diff] [blame] | 597 | def timegm(tuple): |
Guido van Rossum | 4acc25b | 2000-02-02 15:10:15 +0000 | [diff] [blame] | 598 | """Unrelated but handy function to calculate Unix timestamp from GMT.""" |
Alexander Belopolsky | 97958cf | 2010-06-14 18:33:19 +0000 | [diff] [blame] | 599 | year, month, day, hour, minute, second = tuple[:6] |
| 600 | days = datetime.date(year, month, 1).toordinal() - _EPOCH_ORD + day - 1 |
| 601 | hours = days*24 + hour |
| 602 | minutes = hours*60 + minute |
| 603 | seconds = minutes*60 + second |
| 604 | return seconds |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 605 | |
| 606 | |
| 607 | def main(args): |
| 608 | import optparse |
| 609 | parser = optparse.OptionParser(usage="usage: %prog [options] [year [month]]") |
| 610 | parser.add_option( |
| 611 | "-w", "--width", |
| 612 | dest="width", type="int", default=2, |
| 613 | help="width of date column (default 2, text only)" |
| 614 | ) |
| 615 | parser.add_option( |
| 616 | "-l", "--lines", |
| 617 | dest="lines", type="int", default=1, |
| 618 | help="number of lines for each week (default 1, text only)" |
| 619 | ) |
| 620 | parser.add_option( |
| 621 | "-s", "--spacing", |
| 622 | dest="spacing", type="int", default=6, |
| 623 | help="spacing between months (default 6, text only)" |
| 624 | ) |
| 625 | parser.add_option( |
| 626 | "-m", "--months", |
| 627 | dest="months", type="int", default=3, |
| 628 | help="months per row (default 3, text only)" |
| 629 | ) |
| 630 | parser.add_option( |
| 631 | "-c", "--css", |
| 632 | dest="css", default="calendar.css", |
| 633 | help="CSS to use for page (html only)" |
| 634 | ) |
| 635 | parser.add_option( |
| 636 | "-L", "--locale", |
| 637 | dest="locale", default=None, |
| 638 | help="locale to be used from month and weekday names" |
| 639 | ) |
| 640 | parser.add_option( |
| 641 | "-e", "--encoding", |
| 642 | dest="encoding", default=None, |
Senthil Kumaran | 962fed9 | 2011-08-11 09:22:52 +0800 | [diff] [blame] | 643 | help="Encoding to use for output." |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 644 | ) |
| 645 | parser.add_option( |
| 646 | "-t", "--type", |
| 647 | dest="type", default="text", |
| 648 | choices=("text", "html"), |
| 649 | help="output type (text or html)" |
| 650 | ) |
| 651 | |
| 652 | (options, args) = parser.parse_args(args) |
| 653 | |
| 654 | if options.locale and not options.encoding: |
| 655 | parser.error("if --locale is specified --encoding is required") |
| 656 | sys.exit(1) |
| 657 | |
Christian Heimes | 96f3163 | 2007-11-12 01:32:03 +0000 | [diff] [blame] | 658 | locale = options.locale, options.encoding |
| 659 | |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 660 | if options.type == "html": |
| 661 | if options.locale: |
Christian Heimes | 96f3163 | 2007-11-12 01:32:03 +0000 | [diff] [blame] | 662 | cal = LocaleHTMLCalendar(locale=locale) |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 663 | else: |
| 664 | cal = HTMLCalendar() |
| 665 | encoding = options.encoding |
| 666 | if encoding is None: |
| 667 | encoding = sys.getdefaultencoding() |
| 668 | optdict = dict(encoding=encoding, css=options.css) |
Senthil Kumaran | 962fed9 | 2011-08-11 09:22:52 +0800 | [diff] [blame] | 669 | write = sys.stdout.buffer.write |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 670 | if len(args) == 1: |
Senthil Kumaran | 962fed9 | 2011-08-11 09:22:52 +0800 | [diff] [blame] | 671 | write(cal.formatyearpage(datetime.date.today().year, **optdict)) |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 672 | elif len(args) == 2: |
Senthil Kumaran | 962fed9 | 2011-08-11 09:22:52 +0800 | [diff] [blame] | 673 | write(cal.formatyearpage(int(args[1]), **optdict)) |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 674 | else: |
| 675 | parser.error("incorrect number of arguments") |
| 676 | sys.exit(1) |
| 677 | else: |
| 678 | if options.locale: |
Christian Heimes | 96f3163 | 2007-11-12 01:32:03 +0000 | [diff] [blame] | 679 | cal = LocaleTextCalendar(locale=locale) |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 680 | else: |
| 681 | cal = TextCalendar() |
| 682 | optdict = dict(w=options.width, l=options.lines) |
| 683 | if len(args) != 3: |
| 684 | optdict["c"] = options.spacing |
| 685 | optdict["m"] = options.months |
| 686 | if len(args) == 1: |
| 687 | result = cal.formatyear(datetime.date.today().year, **optdict) |
| 688 | elif len(args) == 2: |
| 689 | result = cal.formatyear(int(args[1]), **optdict) |
| 690 | elif len(args) == 3: |
| 691 | result = cal.formatmonth(int(args[1]), int(args[2]), **optdict) |
| 692 | else: |
| 693 | parser.error("incorrect number of arguments") |
| 694 | sys.exit(1) |
Senthil Kumaran | 962fed9 | 2011-08-11 09:22:52 +0800 | [diff] [blame] | 695 | write = sys.stdout.write |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 696 | if options.encoding: |
| 697 | result = result.encode(options.encoding) |
Senthil Kumaran | 962fed9 | 2011-08-11 09:22:52 +0800 | [diff] [blame] | 698 | write = sys.stdout.buffer.write |
| 699 | write(result) |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 700 | |
| 701 | |
| 702 | if __name__ == "__main__": |
| 703 | main(sys.argv) |