NovaBryan/EVE_Dump
Log | Files | 📦 下载最新源码 (.zip) | Refs | README

calendar.py (16953B)


      1 #Embedded file name: C:\BuildAgent\work\20d73f1b24eed06e\eve\release\V24.01\carbon\common\stdlib\calendar.py
      2 import sys
      3 import datetime
      4 import locale as _locale
      5 __all__ = ['IllegalMonthError',
      6  'IllegalWeekdayError',
      7  'setfirstweekday',
      8  'firstweekday',
      9  'isleap',
     10  'leapdays',
     11  'weekday',
     12  'monthrange',
     13  'monthcalendar',
     14  'prmonth',
     15  'month',
     16  'prcal',
     17  'calendar',
     18  'timegm',
     19  'month_name',
     20  'month_abbr',
     21  'day_name',
     22  'day_abbr']
     23 error = ValueError
     24 
     25 class IllegalMonthError(ValueError):
     26 
     27     def __init__(self, month):
     28         self.month = month
     29 
     30     def __str__(self):
     31         return 'bad month number %r; must be 1-12' % self.month
     32 
     33 
     34 class IllegalWeekdayError(ValueError):
     35 
     36     def __init__(self, weekday):
     37         self.weekday = weekday
     38 
     39     def __str__(self):
     40         return 'bad weekday number %r; must be 0 (Monday) to 6 (Sunday)' % self.weekday
     41 
     42 
     43 January = 1
     44 February = 2
     45 mdays = [0,
     46  31,
     47  28,
     48  31,
     49  30,
     50  31,
     51  30,
     52  31,
     53  31,
     54  30,
     55  31,
     56  30,
     57  31]
     58 
     59 class _localized_month:
     60     _months = [ datetime.date(2001, i + 1, 1).strftime for i in range(12) ]
     61     _months.insert(0, lambda x: '')
     62 
     63     def __init__(self, format):
     64         self.format = format
     65 
     66     def __getitem__(self, i):
     67         funcs = self._months[i]
     68         if isinstance(i, slice):
     69             return [ f(self.format) for f in funcs ]
     70         else:
     71             return funcs(self.format)
     72 
     73     def __len__(self):
     74         return 13
     75 
     76 
     77 class _localized_day:
     78     _days = [ datetime.date(2001, 1, i + 1).strftime for i in range(7) ]
     79 
     80     def __init__(self, format):
     81         self.format = format
     82 
     83     def __getitem__(self, i):
     84         funcs = self._days[i]
     85         if isinstance(i, slice):
     86             return [ f(self.format) for f in funcs ]
     87         else:
     88             return funcs(self.format)
     89 
     90     def __len__(self):
     91         return 7
     92 
     93 
     94 day_name = _localized_day('%A')
     95 day_abbr = _localized_day('%a')
     96 month_name = _localized_month('%B')
     97 month_abbr = _localized_month('%b')
     98 MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY = range(7)
     99 
    100 def isleap(year):
    101     return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
    102 
    103 
    104 def leapdays(y1, y2):
    105     y1 -= 1
    106     y2 -= 1
    107     return y2 // 4 - y1 // 4 - (y2 // 100 - y1 // 100) + (y2 // 400 - y1 // 400)
    108 
    109 
    110 def weekday(year, month, day):
    111     return datetime.date(year, month, day).weekday()
    112 
    113 
    114 def monthrange(year, month):
    115     if not 1 <= month <= 12:
    116         raise IllegalMonthError(month)
    117     day1 = weekday(year, month, 1)
    118     ndays = mdays[month] + (month == February and isleap(year))
    119     return (day1, ndays)
    120 
    121 
    122 class Calendar(object):
    123 
    124     def __init__(self, firstweekday = 0):
    125         self.firstweekday = firstweekday
    126 
    127     def getfirstweekday(self):
    128         return self._firstweekday % 7
    129 
    130     def setfirstweekday(self, firstweekday):
    131         self._firstweekday = firstweekday
    132 
    133     firstweekday = property(getfirstweekday, setfirstweekday)
    134 
    135     def iterweekdays(self):
    136         for i in range(self.firstweekday, self.firstweekday + 7):
    137             yield i % 7
    138 
    139     def itermonthdates(self, year, month):
    140         date = datetime.date(year, month, 1)
    141         days = (date.weekday() - self.firstweekday) % 7
    142         date -= datetime.timedelta(days=days)
    143         oneday = datetime.timedelta(days=1)
    144         while True:
    145             yield date
    146             date += oneday
    147             if date.month != month and date.weekday() == self.firstweekday:
    148                 break
    149 
    150     def itermonthdays2(self, year, month):
    151         for date in self.itermonthdates(year, month):
    152             if date.month != month:
    153                 yield (0, date.weekday())
    154             else:
    155                 yield (date.day, date.weekday())
    156 
    157     def itermonthdays(self, year, month):
    158         for date in self.itermonthdates(year, month):
    159             if date.month != month:
    160                 yield 0
    161             else:
    162                 yield date.day
    163 
    164     def monthdatescalendar(self, year, month):
    165         dates = list(self.itermonthdates(year, month))
    166         return [ dates[i:i + 7] for i in range(0, len(dates), 7) ]
    167 
    168     def monthdays2calendar(self, year, month):
    169         days = list(self.itermonthdays2(year, month))
    170         return [ days[i:i + 7] for i in range(0, len(days), 7) ]
    171 
    172     def monthdayscalendar(self, year, month):
    173         days = list(self.itermonthdays(year, month))
    174         return [ days[i:i + 7] for i in range(0, len(days), 7) ]
    175 
    176     def yeardatescalendar(self, year, width = 3):
    177         months = [ self.monthdatescalendar(year, i) for i in range(January, January + 12) ]
    178         return [ months[i:i + width] for i in range(0, len(months), width) ]
    179 
    180     def yeardays2calendar(self, year, width = 3):
    181         months = [ self.monthdays2calendar(year, i) for i in range(January, January + 12) ]
    182         return [ months[i:i + width] for i in range(0, len(months), width) ]
    183 
    184     def yeardayscalendar(self, year, width = 3):
    185         months = [ self.monthdayscalendar(year, i) for i in range(January, January + 12) ]
    186         return [ months[i:i + width] for i in range(0, len(months), width) ]
    187 
    188 
    189 class TextCalendar(Calendar):
    190 
    191     def prweek(self, theweek, width):
    192         print self.formatweek(theweek, width),
    193 
    194     def formatday(self, day, weekday, width):
    195         if day == 0:
    196             s = ''
    197         else:
    198             s = '%2i' % day
    199         return s.center(width)
    200 
    201     def formatweek(self, theweek, width):
    202         return ' '.join((self.formatday(d, wd, width) for d, wd in theweek))
    203 
    204     def formatweekday(self, day, width):
    205         if width >= 9:
    206             names = day_name
    207         else:
    208             names = day_abbr
    209         return names[day][:width].center(width)
    210 
    211     def formatweekheader(self, width):
    212         return ' '.join((self.formatweekday(i, width) for i in self.iterweekdays()))
    213 
    214     def formatmonthname(self, theyear, themonth, width, withyear = True):
    215         s = month_name[themonth]
    216         if withyear:
    217             s = '%s %r' % (s, theyear)
    218         return s.center(width)
    219 
    220     def prmonth(self, theyear, themonth, w = 0, l = 0):
    221         print self.formatmonth(theyear, themonth, w, l),
    222 
    223     def formatmonth(self, theyear, themonth, w = 0, l = 0):
    224         w = max(2, w)
    225         l = max(1, l)
    226         s = self.formatmonthname(theyear, themonth, 7 * (w + 1) - 1)
    227         s = s.rstrip()
    228         s += '\n' * l
    229         s += self.formatweekheader(w).rstrip()
    230         s += '\n' * l
    231         for week in self.monthdays2calendar(theyear, themonth):
    232             s += self.formatweek(week, w).rstrip()
    233             s += '\n' * l
    234 
    235         return s
    236 
    237     def formatyear(self, theyear, w = 2, l = 1, c = 6, m = 3):
    238         w = max(2, w)
    239         l = max(1, l)
    240         c = max(2, c)
    241         colwidth = (w + 1) * 7 - 1
    242         v = []
    243         a = v.append
    244         a(repr(theyear).center(colwidth * m + c * (m - 1)).rstrip())
    245         a('\n' * l)
    246         header = self.formatweekheader(w)
    247         for i, row in enumerate(self.yeardays2calendar(theyear, m)):
    248             months = range(m * i + 1, min(m * (i + 1) + 1, 13))
    249             a('\n' * l)
    250             names = (self.formatmonthname(theyear, k, colwidth, False) for k in months)
    251             a(formatstring(names, colwidth, c).rstrip())
    252             a('\n' * l)
    253             headers = (header for k in months)
    254             a(formatstring(headers, colwidth, c).rstrip())
    255             a('\n' * l)
    256             height = max((len(cal) for cal in row))
    257             for j in range(height):
    258                 weeks = []
    259                 for cal in row:
    260                     if j >= len(cal):
    261                         weeks.append('')
    262                     else:
    263                         weeks.append(self.formatweek(cal[j], w))
    264 
    265                 a(formatstring(weeks, colwidth, c).rstrip())
    266                 a('\n' * l)
    267 
    268         return ''.join(v)
    269 
    270     def pryear(self, theyear, w = 0, l = 0, c = 6, m = 3):
    271         print self.formatyear(theyear, w, l, c, m)
    272 
    273 
    274 class HTMLCalendar(Calendar):
    275     cssclasses = ['mon',
    276      'tue',
    277      'wed',
    278      'thu',
    279      'fri',
    280      'sat',
    281      'sun']
    282 
    283     def formatday(self, day, weekday):
    284         if day == 0:
    285             return '<td class="noday">&nbsp;</td>'
    286         else:
    287             return '<td class="%s">%d</td>' % (self.cssclasses[weekday], day)
    288 
    289     def formatweek(self, theweek):
    290         s = ''.join((self.formatday(d, wd) for d, wd in theweek))
    291         return '<tr>%s</tr>' % s
    292 
    293     def formatweekday(self, day):
    294         return '<th class="%s">%s</th>' % (self.cssclasses[day], day_abbr[day])
    295 
    296     def formatweekheader(self):
    297         s = ''.join((self.formatweekday(i) for i in self.iterweekdays()))
    298         return '<tr>%s</tr>' % s
    299 
    300     def formatmonthname(self, theyear, themonth, withyear = True):
    301         if withyear:
    302             s = '%s %s' % (month_name[themonth], theyear)
    303         else:
    304             s = '%s' % month_name[themonth]
    305         return '<tr><th colspan="7" class="month">%s</th></tr>' % s
    306 
    307     def formatmonth(self, theyear, themonth, withyear = True):
    308         v = []
    309         a = v.append
    310         a('<table border="0" cellpadding="0" cellspacing="0" class="month">')
    311         a('\n')
    312         a(self.formatmonthname(theyear, themonth, withyear=withyear))
    313         a('\n')
    314         a(self.formatweekheader())
    315         a('\n')
    316         for week in self.monthdays2calendar(theyear, themonth):
    317             a(self.formatweek(week))
    318             a('\n')
    319 
    320         a('</table>')
    321         a('\n')
    322         return ''.join(v)
    323 
    324     def formatyear(self, theyear, width = 3):
    325         v = []
    326         a = v.append
    327         width = max(width, 1)
    328         a('<table border="0" cellpadding="0" cellspacing="0" class="year">')
    329         a('\n')
    330         a('<tr><th colspan="%d" class="year">%s</th></tr>' % (width, theyear))
    331         for i in range(January, January + 12, width):
    332             months = range(i, min(i + width, 13))
    333             a('<tr>')
    334             for m in months:
    335                 a('<td>')
    336                 a(self.formatmonth(theyear, m, withyear=False))
    337                 a('</td>')
    338 
    339             a('</tr>')
    340 
    341         a('</table>')
    342         return ''.join(v)
    343 
    344     def formatyearpage(self, theyear, width = 3, css = 'calendar.css', encoding = None):
    345         if encoding is None:
    346             encoding = sys.getdefaultencoding()
    347         v = []
    348         a = v.append
    349         a('<?xml version="1.0" encoding="%s"?>\n' % encoding)
    350         a('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n')
    351         a('<html>\n')
    352         a('<head>\n')
    353         a('<meta http-equiv="Content-Type" content="text/html; charset=%s" />\n' % encoding)
    354         if css is not None:
    355             a('<link rel="stylesheet" type="text/css" href="%s" />\n' % css)
    356         a('<title>Calendar for %d</title>\n' % theyear)
    357         a('</head>\n')
    358         a('<body>\n')
    359         a(self.formatyear(theyear, width))
    360         a('</body>\n')
    361         a('</html>\n')
    362         return ''.join(v).encode(encoding, 'xmlcharrefreplace')
    363 
    364 
    365 class TimeEncoding:
    366 
    367     def __init__(self, locale):
    368         self.locale = locale
    369 
    370     def __enter__(self):
    371         self.oldlocale = _locale.getlocale(_locale.LC_TIME)
    372         _locale.setlocale(_locale.LC_TIME, self.locale)
    373 
    374     def __exit__(self, *args):
    375         _locale.setlocale(_locale.LC_TIME, self.oldlocale)
    376 
    377 
    378 class LocaleTextCalendar(TextCalendar):
    379 
    380     def __init__(self, firstweekday = 0, locale = None):
    381         TextCalendar.__init__(self, firstweekday)
    382         if locale is None:
    383             locale = _locale.getdefaultlocale()
    384         self.locale = locale
    385 
    386     def formatweekday(self, day, width):
    387         with TimeEncoding(self.locale) as encoding:
    388             if width >= 9:
    389                 names = day_name
    390             else:
    391                 names = day_abbr
    392             name = names[day]
    393             if encoding is not None:
    394                 name = name.decode(encoding)
    395             return name[:width].center(width)
    396 
    397     def formatmonthname(self, theyear, themonth, width, withyear = True):
    398         with TimeEncoding(self.locale) as encoding:
    399             s = month_name[themonth]
    400             if encoding is not None:
    401                 s = s.decode(encoding)
    402             if withyear:
    403                 s = '%s %r' % (s, theyear)
    404             return s.center(width)
    405 
    406 
    407 class LocaleHTMLCalendar(HTMLCalendar):
    408 
    409     def __init__(self, firstweekday = 0, locale = None):
    410         HTMLCalendar.__init__(self, firstweekday)
    411         if locale is None:
    412             locale = _locale.getdefaultlocale()
    413         self.locale = locale
    414 
    415     def formatweekday(self, day):
    416         with TimeEncoding(self.locale) as encoding:
    417             s = day_abbr[day]
    418             if encoding is not None:
    419                 s = s.decode(encoding)
    420             return '<th class="%s">%s</th>' % (self.cssclasses[day], s)
    421 
    422     def formatmonthname(self, theyear, themonth, withyear = True):
    423         with TimeEncoding(self.locale) as encoding:
    424             s = month_name[themonth]
    425             if encoding is not None:
    426                 s = s.decode(encoding)
    427             if withyear:
    428                 s = '%s %s' % (s, theyear)
    429             return '<tr><th colspan="7" class="month">%s</th></tr>' % s
    430 
    431 
    432 c = TextCalendar()
    433 firstweekday = c.getfirstweekday
    434 
    435 def setfirstweekday(firstweekday):
    436     try:
    437         firstweekday.__index__
    438     except AttributeError:
    439         raise IllegalWeekdayError(firstweekday)
    440 
    441     if not MONDAY <= firstweekday <= SUNDAY:
    442         raise IllegalWeekdayError(firstweekday)
    443     c.firstweekday = firstweekday
    444 
    445 
    446 monthcalendar = c.monthdayscalendar
    447 prweek = c.prweek
    448 week = c.formatweek
    449 weekheader = c.formatweekheader
    450 prmonth = c.prmonth
    451 month = c.formatmonth
    452 calendar = c.formatyear
    453 prcal = c.pryear
    454 _colwidth = 20
    455 _spacing = 6
    456 
    457 def format(cols, colwidth = _colwidth, spacing = _spacing):
    458     print formatstring(cols, colwidth, spacing)
    459 
    460 
    461 def formatstring(cols, colwidth = _colwidth, spacing = _spacing):
    462     spacing *= ' '
    463     return spacing.join((c.center(colwidth) for c in cols))
    464 
    465 
    466 EPOCH = 1970
    467 _EPOCH_ORD = datetime.date(EPOCH, 1, 1).toordinal()
    468 
    469 def timegm(tuple):
    470     year, month, day, hour, minute, second = tuple[:6]
    471     days = datetime.date(year, month, 1).toordinal() - _EPOCH_ORD + day - 1
    472     hours = days * 24 + hour
    473     minutes = hours * 60 + minute
    474     seconds = minutes * 60 + second
    475     return seconds
    476 
    477 
    478 def main(args):
    479     import optparse
    480     parser = optparse.OptionParser(usage='usage: %prog [options] [year [month]]')
    481     parser.add_option('-w', '--width', dest='width', type='int', default=2, help='width of date column (default 2, text only)')
    482     parser.add_option('-l', '--lines', dest='lines', type='int', default=1, help='number of lines for each week (default 1, text only)')
    483     parser.add_option('-s', '--spacing', dest='spacing', type='int', default=6, help='spacing between months (default 6, text only)')
    484     parser.add_option('-m', '--months', dest='months', type='int', default=3, help='months per row (default 3, text only)')
    485     parser.add_option('-c', '--css', dest='css', default='calendar.css', help='CSS to use for page (html only)')
    486     parser.add_option('-L', '--locale', dest='locale', default=None, help='locale to be used from month and weekday names')
    487     parser.add_option('-e', '--encoding', dest='encoding', default=None, help='Encoding to use for output')
    488     parser.add_option('-t', '--type', dest='type', default='text', choices=('text', 'html'), help='output type (text or html)')
    489     options, args = parser.parse_args(args)
    490     if options.locale and not options.encoding:
    491         parser.error('if --locale is specified --encoding is required')
    492         sys.exit(1)
    493     locale = (options.locale, options.encoding)
    494     if options.type == 'html':
    495         if options.locale:
    496             cal = LocaleHTMLCalendar(locale=locale)
    497         else:
    498             cal = HTMLCalendar()
    499         encoding = options.encoding
    500         if encoding is None:
    501             encoding = sys.getdefaultencoding()
    502         optdict = dict(encoding=encoding, css=options.css)
    503         if len(args) == 1:
    504             print cal.formatyearpage(datetime.date.today().year, **optdict)
    505         elif len(args) == 2:
    506             print cal.formatyearpage(int(args[1]), **optdict)
    507         else:
    508             parser.error('incorrect number of arguments')
    509             sys.exit(1)
    510     else:
    511         if options.locale:
    512             cal = LocaleTextCalendar(locale=locale)
    513         else:
    514             cal = TextCalendar()
    515         optdict = dict(w=options.width, l=options.lines)
    516         if len(args) != 3:
    517             optdict['c'] = options.spacing
    518             optdict['m'] = options.months
    519         if len(args) == 1:
    520             result = cal.formatyear(datetime.date.today().year, **optdict)
    521         elif len(args) == 2:
    522             result = cal.formatyear(int(args[1]), **optdict)
    523         elif len(args) == 3:
    524             result = cal.formatmonth(int(args[1]), int(args[2]), **optdict)
    525         else:
    526             parser.error('incorrect number of arguments')
    527             sys.exit(1)
    528         if options.encoding:
    529             result = result.encode(options.encoding)
    530         print result
    531 
    532 
    533 if __name__ == '__main__':
    534     main(sys.argv)