我们从Python开源项目中,提取了以下42个代码示例,用于说明如何使用calendar.Calendar()。
def test_localecalendars(self): # ensure that Locale{Text,HTML}Calendar resets the locale properly # (it is still not thread-safe though) old_october = calendar.TextCalendar().formatmonthname(2010, 10, 10) try: cal = calendar.LocaleTextCalendar(locale='') local_weekday = cal.formatweekday(1, 10) local_month = cal.formatmonthname(2010, 10, 10) except locale.Error: # cannot set the system default locale -- skip rest of test raise unittest.SkipTest('cannot set the system default locale') # should be encodable local_weekday.encode('utf-8') local_month.encode('utf-8') self.assertEqual(len(local_weekday), 10) self.assertGreaterEqual(len(local_month), 10) cal = calendar.LocaleHTMLCalendar(locale='') local_weekday = cal.formatweekday(1) local_month = cal.formatmonthname(2010, 10) # should be encodable local_weekday.encode('utf-8') local_month.encode('utf-8') new_october = calendar.TextCalendar().formatmonthname(2010, 10, 10) self.assertEqual(old_october, new_october)
def test_locale_calendars(self): # ensure that Locale{Text,HTML}Calendar resets the locale properly # (it is still not thread-safe though) old_october = calendar.TextCalendar().formatmonthname(2010, 10, 10) try: cal = calendar.LocaleTextCalendar(locale='') local_weekday = cal.formatweekday(1, 10) local_month = cal.formatmonthname(2010, 10, 10) except locale.Error: # cannot set the system default locale -- skip rest of test raise unittest.SkipTest('cannot set the system default locale') self.assertIsInstance(local_weekday, str) self.assertIsInstance(local_month, str) self.assertEqual(len(local_weekday), 10) self.assertGreaterEqual(len(local_month), 10) cal = calendar.LocaleHTMLCalendar(locale='') local_weekday = cal.formatweekday(1) local_month = cal.formatmonthname(2010, 10) self.assertIsInstance(local_weekday, str) self.assertIsInstance(local_month, str) new_october = calendar.TextCalendar().formatmonthname(2010, 10, 10) self.assertEqual(old_october, new_october)
def __init__(self, callback, year=None, month=None, day=None, firstweekday=0, **kwargs): self.callback = callback self.cal = calendar.Calendar(firstweekday) self.sel_year = year if year else self.today.year self.sel_month = month if month else self.today.month self.sel_day = day if day else self.today.day self.month = self.sel_month self.year = self.sel_year self.day = self.sel_day super(MDDatePicker, self).__init__(**kwargs) self.selector = DaySelector(parent=self) self.generate_cal_widgets() self.update_cal_matrix(self.sel_year, self.sel_month) self.set_month_day(self.sel_day) self.selector.update()
def get_days_of_the_month(month, year = date.today().year): #get current year if year is None: year = date.today().year mappings = {_('January'): 1, _('February'): 2, _('March'): 3, _('April'): 4, _('May'): 5, _('June'): 6, _('July'): 7 , _('August'): 8, _('September'): 9, _('October'): 10, _('November'): 11, _('December'): 12} c = calendar.Calendar() days = c.itermonthdays(int(year), mappings[_(month)]) days_set = set() for day in days: days_set.add(day) days_set.remove(0) #because 0 is not aan actual day from that month return days_set
def __init__(self, year): self.year = year self.year_calendar = ( calendar.Calendar().yeardatescalendar(self.year, 12)[0] )
def calendar(self, month=None, year=None): return Calendar(month, year)
def dbtc(self): """output the calendar of current year in text with month follow by days on each row""" current_yr = datetime.date.today().year global DONE_SYMBOL DONE_SYMBOL = self.view.settings().get("done_symbol") init_msg = "** {0} **".format(INITIAL_MESSAGE).center(CALENDAR_WIDTH) year = "{year}\n".format(year=current_yr).rjust(8, ' ') txt_builder = [] txt_builder.append(init_msg) txt_builder.append("\n\n") txt_builder.append(year) cal = calendar.Calendar(calendar.MONDAY) for m, month_name in MONTHS.items(): month = cal.itermonthdays(current_yr, m) days = "".join( [get_weekday_format(current_yr, m, day) for day in month if day != 0] ) txt_builder.append("{month_name}{days}\n".format(month_name=month_name, days=days)) return "".join(txt_builder)
def GetFirstSundayOfMonth(year, month): """Returns the first sunday of the given month of the given year. >>> GetFirstSundayOfMonth(2016, 2) 7 >>> GetFirstSundayOfMonth(2016, 3) 6 >>> GetFirstSundayOfMonth(2000, 1) 2 """ weeks = calendar.Calendar().monthdays2calendar(year, month) # Return the first day in the first week that is a Sunday. return [date_day[0] for date_day in weeks[0] if date_day[1] == 6][0]
def index(year): conn = pymongo.MongoClient() db = conn.test cal = Calendar(0) try: if not year: year = date.today().year cal_list = [cal.monthdatescalendar(year, i+1) for i in xrange(12)] except Exception, e: abort(404) else: records = [record for record in db.myCollections.find()] return render_template('cal.html', year=year, cal=cal_list, events=records, cur_month=datetime.datetime.now().month) abort(404)
def getdistonmonth(): config = if_not_exists_to_create_config() nvisitors = Visitor.objects.count() from calendar import Calendar c = Calendar() # This month now = timezone.now() padmonth = padtime(now.month) weeks = c.monthdatescalendar(year=now.year, month=now.month) for week in weeks: for i, day in enumerate(week): iday = day.day q = 'SELECT * FROM visitor_visitor WHERE visit_date LIKE "{0}-{1}-{2}%%"'.format(now.year, padmonth, padtime(iday)) total = len(list(Visitor.objects.raw(q))) per = toper(nvisitors, total) image = None if len(settings.MEDIA_URL) and len(settings.MEDIA_ROOT): fname = 'c{0}.png'.format(padtime(iday)) url = os.path.join(settings.MEDIA_URL, config.media_directory, fname) savepath = os.path.join(settings.MEDIA_ROOT, config.media_directory, fname) savecalrect(savepath, nvisitors, total) image = { # TODO: Remove /media 'url': url, } week[i] = { 'day': iday, 'total': total, 'per': per, 'image': image, } return weeks
def test_itermonthdates(self): # ensure itermonthdates doesn't overflow after datetime.MAXYEAR # see #15421 list(calendar.Calendar().itermonthdates(datetime.MAXYEAR, 12))
def test_itermonthdays(self): for firstweekday in range(7): cal = calendar.Calendar(firstweekday) # Test the extremes, see #28253 and #26650 for y, m in [(1, 1), (9999, 12)]: days = list(cal.itermonthdays(y, m)) self.assertIn(len(days), (35, 42)) # Test a short month cal = calendar.Calendar(firstweekday=3) days = list(cal.itermonthdays(2001, 2)) self.assertEqual(days, list(range(1, 29)))
def test_itermonthdays2(self): for firstweekday in range(7): cal = calendar.Calendar(firstweekday) # Test the extremes, see #28253 and #26650 for y, m in [(1, 1), (9999, 12)]: days = list(cal.itermonthdays2(y, m)) self.assertEqual(days[0][1], firstweekday) self.assertEqual(days[-1][1], (firstweekday - 1) % 7)
def test_option_type(self): self.assertFailure('-t') self.assertFailure('--type') self.assertFailure('-t', 'spam') stdout = self.run_ok('--type', 'text', '2004') self.assertEqual(stdout.strip(), conv(result_2004_text).strip()) stdout = self.run_ok('--type', 'html', '2004') self.assertEqual(stdout[:6], b'<?xml ') self.assertIn(b'<title>Calendar for 2004</title>', stdout)
def test_yeardatescalendar(self): def shrink(cal): return [[[' '.join('{:02d}/{:02d}/{}'.format( d.month, d.day, str(d.year)[-2:]) for d in z) for z in y] for y in x] for x in cal] self.assertEqual( shrink(calendar.Calendar().yeardatescalendar(2004)), result_2004_dates )
def test_yeardayscalendar(self): self.assertEqual( calendar.Calendar().yeardayscalendar(2004), result_2004_days )
def tandem_choose_date(request, year=datetime.now().year, month=datetime.now().month, template_name='signup/tandem_choose_date.html'): month, year = int(month), int(year) c = calendar.Calendar() c.setfirstweekday(calendar.SUNDAY) cal = c.monthdatescalendar(year, month) _events = TandemDay.objects.filter(date__range=(cal[0][0], cal[len(cal) - 1][6])) events = {} for e in _events: if e.date.month not in events: events[e.date.month] = {} if e.date.day not in events[e.date.month]: events[e.date.month][e.date.day] = [] events[e.date.month][e.date.day].append(e) print(events) data = {} data['title'] = "Tandem Sign Up" data['month_name'] = calendar.month_name[month] data['year'] = year data['month'] = month data['previous'] = {'month': (month - 1 + 11) % 12 + 1, 'year': year - (1 if month == 1 else 0)} data['next'] = {'month': (month - 1 + 1) % 12 + 1, 'year': year + (1 if month == 12 else 0)} data['calendar'] = cal data['events'] = events data['nofollow'] = (True if year < 2017 or year > datetime.now().year + 2 else False) return render(request, template_name, data)
def test_option_type(self): self.assertFailure('-t') self.assertFailure('--type') self.assertFailure('-t', 'spam') stdout = self.run_ok('--type', 'text', '2004') self.assertEqual(stdout, conv(result_2004_text)) stdout = self.run_ok('--type', 'html', '2004') self.assertEqual(stdout[:6], b'<?xml ') self.assertIn(b'<title>Calendar for 2004</title>', stdout)
def make_calendar(date): date_object = datetime.strptime(date, FORMAT_DATE) calendar_obj = calendar.Calendar().monthdayscalendar(date_object.year, date_object.month) return [[x if x != 0 else '' for x in week] for week in calendar_obj], date_object.month, date_object.year
def get_text_calendar_dates(date1, date2, cols=3): """ Get array of datetimes between two dates suitable for formatting """ """ The return value is a list of years. Each year contains a list of month rows. Each month row contains cols months (default 3). Each month contains list of 6 weeks (the max possible). Each week contains 1 to 7 days. Days are datetime.date objects. """ year1 = date1.year year2 = date2.year # start and end rows row1 = int((date1.month - 1) / cols) row2 = int((date2.month - 1) / cols) + 1 # generate base calendar array Calendar = calendar.Calendar() cal = [] for yr in range(year1, year2+1): ycal = Calendar.yeardatescalendar(yr, width=cols) if yr == year1 and yr == year2: ycal = ycal[row1:row2] elif yr == year1: ycal = ycal[row1:] elif yr == year2: ycal = ycal[:row2] cal.append(ycal) return cal