我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用calendar.month_name()。
def get_context_data(self,**kwargs): instructor = self.object context = {} context.update({ 'instructor': instructor, 'prior_series': Event.objects.filter(startTime__lte=timezone.now(),eventstaffmember__staffMember=instructor).order_by('-startTime'), 'upcoming_series': Event.objects.filter(startTime__gt=timezone.now(),eventstaffmember__staffMember=instructor).order_by('-startTime'), }) if context['prior_series']: context.update({'first_series': context['prior_series'].last(),}) context.update({ 'teaching_since': month_name[context['first_series'].month] + ' ' + str(context['first_series'].year), 'student_count': sum([x.numRegistered for x in context['prior_series']]), }) context.update({'series_count': len(context['prior_series']) + len(context['upcoming_series'])}) # Note: This get the detailview's context, not all the mixins. Supering itself led to an infinite loop. return super(DetailView, self).get_context_data(**context)
def get(self,request,*args,**kwargs): # These are passed via the URL year = self.kwargs.get('year') month = self.kwargs.get('month') slug = self.kwargs.get('slug','') try: month_number = list(month_name).index(month or 0) except ValueError: raise Http404(_('Invalid month.')) seriesset = get_list_or_404(Series,~Q(status=Event.RegStatus.hidden),~Q(status=Event.RegStatus.linkOnly),year=year or None,month=month_number or None,classDescription__slug=slug) # This will pass through to the context data by default kwargs.update({'seriesset': seriesset}) # For each Series in the set, add a button to the toolbar to edit the Series details if hasattr(request,'user') and request.user.has_perm('core.change_series'): for this_series in seriesset: this_title = _('Edit Class Details') if len(seriesset) > 1: this_title += ' (#%s)' % this_series.id request.toolbar.add_button(this_title, reverse('admin:core_series_change', args=([this_series.id,])), side=RIGHT) return super(IndividualClassView,self).get(request,*args,**kwargs)
def eventregistration_list(self,obj): eregs = obj.eventregistration_set.all() if not eregs: return '' return_string = '<ul>' for ereg in eregs: this_string = '<li>' if ereg.cancelled: this_string += '<em>%s</em> ' % _('CANCELLED:') if ereg.dropIn: this_string += '<em>%s</em> ' % _('DROP-IN:') if ereg.event.month: this_string += '%s %s, %s</li>' % (month_name[ereg.event.month], ereg.event.year, ereg.event.name) else: this_string += '%s</li>' % ereg.event.name return_string += this_string return return_string
def bdays_month(month): if month not in range(1, 13): abort(400, 'Not a valid month') # SO questions/36155332 _, num_days = calendar.monthrange(THIS_YEAR, month) start = date(THIS_YEAR, month, 1) end = date(THIS_YEAR, month, num_days) now = _get_current_date() # TODO: some duplication here with index() bdays = (Birthday.query.filter(Birthday.bday <= end) .filter(Birthday.bday >= start)) month_name = calendar.month_name[month][:3] return render_template("index.html", data=bdays, now=now, active_tab=month_name, tabs=TABS)
def _set_league_sport_map(league, sport, start_month=None, end_month=None): '''Set league to sport mapping only if current date within range''' if not start_month or not end_month: # year-round league LEAGUE_SPORT_MAP[league] = sport return month_to_num = dict((v,k) for k,v in enumerate(calendar.month_name)) start_month_num = month_to_num[start_month] end_month_num = month_to_num[end_month] current_month_num = datetime.datetime.utcnow().month if start_month_num <= current_month_num <= end_month_num: LEAGUE_SPORT_MAP[league] = sport return if end_month_num < start_month_num: # range wraps around year if start_month_num <= current_month_num or current_month_num <= end_month_num: LEAGUE_SPORT_MAP[league] = sport return
def test_using_filters(self): now = datetime.now() client = self.get_ussd_client() # dial in response = client.send('1') self.assertEqual( "The date today is {now}. We are on the {now_month} th month " "and we are on year {now_year}. Month in words is " "{now_month_name}. And day in words " "{now_day_name}. And next month {three_months}\n" "Testing striping date. After striping this " "date 2017-01-20 we should get the year, month and day. " "The day is {strip_day_name}\n".format( now=now, now_month=now.month, now_year=now.year, now_month_name=calendar.month_name[now.month], now_day_name=now.strftime("%A"), three_months=calendar.month_name[now.month + 3], strip_day_name=20 ), response )
def calendar(self): pid = int(self.p['pid']) if 'pid' in self.p else -1 now = datetime.datetime.now() year = int(self.p['year']) if 'year' in self.p else now.year month = int(self.p['month']) if 'month' in self.p else now.month show_subtasks = True if 'show' in self.p else False project_a = projects_sql(self.gid) if int(pid) > 0: project = project_name_sql(self.gid, pid) else: project = "" calendar_a = calendar_sql(self.gid, pid, year, month, show_subtasks) msg_a = msg_sql(self.gid) return {'user': self.user, 'project_a': project_a, 'pid': pid, 'project': project, 'month_num': month, 'month_name': calendar.month_name[month], 'year': year, 'calendar_a': calendar_a, 'msg_a': msg_a}
def test_month_name(self): import calendar m = datetime.now().month expected = calendar.month_name[m] result = month_name() self.assertEqual(expected, result)
def test_last_month_name(self): import calendar m = (datetime.now().month - 2) % 12 + 1 expected = calendar.month_name[m] result = last_month_name() self.assertEqual(expected, result)
def __calc_month(self): # Set self.f_month and self.a_month using the calendar module. a_month = [calendar.month_abbr[i].lower() for i in range(13)] f_month = [calendar.month_name[i].lower() for i in range(13)] self.a_month = a_month self.f_month = f_month
def get_month_number(self, month): names = dict((v, k) for k, v in enumerate(calendar.month_name)) abbrs = dict((v, k) for k, v in enumerate(calendar.month_abbr)) month_str = month.title() try: return names[month_str] except KeyError: try: return abbrs[month_str] except KeyError: return 0
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 name(self): return standardlib_calendar.month_name[self.start.month]
def test_name(self): # abbreviations for i, name in enumerate(calendar.month_abbr[1:]): self.assertEquals(MonthSetBuilder().build(name), {i + 1}) self.assertEquals(MonthSetBuilder().build(name.lower()), {i + 1}) self.assertEquals(MonthSetBuilder().build(name.upper()), {i + 1}) # full names for i, name in enumerate(calendar.month_name[1:]): self.assertEquals(MonthSetBuilder().build(name), {i + 1}) self.assertEquals(MonthSetBuilder().build(name.lower()), {i + 1}) self.assertEquals(MonthSetBuilder().build(name.upper()), {i + 1})
def textDateToInt(txtDate): for index, item in enumerate(calendar.month_name): if item[:3] == txtDate: if len(str(index)) == 1: return "0" + str(index) else: return str(index) # sort by value of date inside each dict inside parent dict
def get_month_number(self, month): """Take a string month and return its numberic.""" months = {v: k for k, v in enumerate(calendar.month_name)} return months[month]
def MonthlyPerformanceJSON(request): series = request.GET.get('series') if series not in ['AvgStudents','Registrations','EventRegistrations','Hours','StudentHours']: series = 'EventRegistrations' yearTotals = getMonthlyPerformance()[series] # Return JSON as lists, not as dictionaries, for c3.js # yearTotals_list = [dict(v,**{'year':k}) for k, v in yearTotals.items()] # Now make the lists so that there is one row per month, not one row per year, # to make things easier for working with c3.js.yearTotals monthTotals_list = [] years = list(set([k for k,v in yearTotals.items()])) # Only include calendar months for graphing for month in range(1,13): this_month_data = {'month': month, 'month_name': month_name[month]} for year in years: this_month_data[year] = yearTotals[year].get(month) monthTotals_list.append(this_month_data) monthTotals_list_sorted = sorted(monthTotals_list, key=lambda k: k['month']) return JsonResponse(monthTotals_list_sorted,safe=False)
def MonthlyPerformanceCSV(request): # Create the HttpResponse object with the appropriate CSV header. response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="monthlyPerformance.csv"' writer = csv.writer(response) yearTotals = getMonthlyPerformance() all_years = [k for k in yearTotals['Hours'].keys() if k != 'MonthlyAverage'] all_years.sort() # Write headers first headers_list = ['Data Series','Month','All-Time Avg.'] for year in all_years: headers_list.append(str(year)) writer.writerow(headers_list) # Note: These are not translated because the chart Javascript looks for these keys yearTotals_keys = { 'Total Student-Hours': 'StudentHours', 'Avg. Students/Hour': 'AvgStudents', 'Hours of Instruction': 'Hours', 'Unique Registrations': 'Registrations', 'Total Students': 'EventRegistrations', } for series,key in yearTotals_keys.items(): for month in range(1,13): this_row = [ series, month_name[month], yearTotals[key]['MonthlyAverage'][month], ] for year in all_years: this_row.append(yearTotals[key][year][month]) writer.writerow(this_row) return response
def get_form_kwargs(self, **kwargs): ''' Get the list of recent months and recent series to pass to the form ''' numMonths = 12 lastStart = Event.objects.annotate(Min('eventoccurrence__startTime')).order_by('-eventoccurrence__startTime__min').values_list('eventoccurrence__startTime__min',flat=True).first() if lastStart: month = lastStart.month year = lastStart.year else: month = timezone.now().month year = timezone.now().year months = [('',_('None'))] for i in range(0,numMonths): newmonth = (month - i - 1) % 12 + 1 newyear = year if month - i - 1 < 0: newyear = year - 1 newdate = datetime(year=newyear,month=newmonth,day=1) newdateStr = newdate.strftime("%m-%Y") monthStr = newdate.strftime("%B, %Y") months.append((newdateStr,monthStr)) cutoff = timezone.now() - timedelta(days=120) allEvents = Event.objects.filter(startTime__gte=cutoff).order_by('-startTime') kwargs = super(SendEmailView, self).get_form_kwargs(**kwargs) kwargs.update({ "months": months, "recentseries": [('','None')] + [(x.id,'%s %s: %s' % (month_name[x.month],x.year,x.name)) for x in allEvents], "customers": self.customers, }) return kwargs
def getMonthName(self): ''' This exists as a separate method because sometimes events should really belong to more than one month (e.g. class series that persist over multiple months). ''' class_counter = Counter([(x.startTime.year, x.startTime.month) for x in self.eventoccurrence_set.all()]) multiclass_months = [x[0] for x in class_counter.items() if x[1] > 1] all_months = [x[0] for x in class_counter.items()] if multiclass_months: multiclass_months.sort() return '/'.join([month_name[x[1]] for x in multiclass_months]) else: return month_name[min(all_months)[1]]
def url(self): if self.status not in [self.RegStatus.hidden, self.RegStatus.linkOnly]: return reverse('classView',args=[self.year,month_name[self.month or 0] or None,self.classDescription.slug])
def __str__(self): if self.month and self.year and self.classDescription: # In case of unsaved series, month and year are not yet set. return month_name[self.month or 0] + ' ' + str(self.year) + ": " + self.classDescription.title elif self.classDescription: return str(_('Class Series: %s' % self.classDescription.title)) else: return str(_('Class Series'))
def __str__(self): replacements = { 'name': self.staffMember.fullName, 'subbed': _(' subbed: '), 'month': month_name[self.event.month or 0], 'year': self.event.year, } if not self.replacedStaffMember: return '%(name)s %(subbed)s: %(month)s %(year)s' % replacements replacements.update({'subbed': _(' subbed for '), 'staffMember': self.replacedStaffMember.staffMember.fullName}) return '%(name)s %(subbed)s %(staffMember)s: %(month)s %(year)s' % replacements
def readable_month(month): try: return month_name[month] except (TypeError,IndexError): return None
def series_month(self,obj): return '%s %s' % (month_name[obj.month or 0],obj.year or '')
def render_to_csv(self, context): statement = context['statement'] response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="financialStatementByMonth.csv"' writer = csv.writer(response, csv.excel) response.write(u'\ufeff'.encode('utf8')) # BOM (optional...Excel needs it to open UTF-8 file properly) header_list = [ _('Month Name'), _('Revenues: Net'), _('Expenses: Instruction'), _('Expenses: Venue'), _('Expenses: Other'), _('Expenses: Total'), _('Registrations'), _('Net Profit'), ] writer.writerow(header_list) for x in statement['statementByMonth']: this_row_data = [ x['month_name'], x['revenues'], x['expenses']['instruction'], x['expenses']['venue'], x['expenses']['other'], x['expenses']['total'], x['registrations'], x['net_profit'], ] writer.writerow(this_row_data) return response
def get_invoice(user_name, user_id, month): html = """ <p>Anzee Corporation</p><br> <b><p>Account Name: """ + user_name + """</p> <p>Invoice for month of: """ + str(calendar.month_name[month]) + """</p></b> <br><br> <p><b>Payments and Usage:</b></p> <table align="center" width="50%"> <thead> <tr> <th align="left" width="50%">Charge Type</th> <th align="right" width="50%">Amount</th> </tr> </thead> <tbody> <tr> <td>Payments Done</td> <td align="right">$""" + str(get_payments(user_id, month)) + """</td> </tr> <tr> <td>Total Usage</td> <td align="right">$""" + str(get_usage(user_id, month)) + """</td> </tr> </tbody> </table> <br><br> """ return html
def create_calendar(year,month): markup = types.InlineKeyboardMarkup() #First row - Month and Year row=[] row.append(types.InlineKeyboardButton(calendar.month_name[month]+" "+str(year),callback_data="ignore")) markup.row(*row) #Second row - Week Days week_days=["M","T","W","R","F","S","U"] row=[] for day in week_days: row.append(types.InlineKeyboardButton(day,callback_data="ignore")) markup.row(*row) my_calendar = calendar.monthcalendar(year, month) for week in my_calendar: row=[] for day in week: if(day==0): row.append(types.InlineKeyboardButton(" ",callback_data="ignore")) else: row.append(types.InlineKeyboardButton(str(day),callback_data="calendar-day-"+str(day))) markup.row(*row) #Last row - Buttons row=[] row.append(types.InlineKeyboardButton("<",callback_data="previous-month")) row.append(types.InlineKeyboardButton(" ",callback_data="ignore")) row.append(types.InlineKeyboardButton(">",callback_data="next-month")) markup.row(*row) return markup
def get_date_form(answer=None, error_messages=None): """ Returns a date form metaclass with appropriate validators. Used in both date and date range form creation. :param error_messages: The messages during validation :param answer: The answer on which to base this form :return: The generated DateForm metaclass """ class DateForm(Form): day = StringField() year = StringField() validate_with = [OptionalForm()] if not error_messages: date_messages = {} else: date_messages = error_messages.copy() if answer['mandatory'] is True: if 'validation' in answer and 'messages' in answer['validation'] \ and 'MANDATORY_DATE' in answer['validation']['messages']: date_messages['MANDATORY_DATE'] = answer['validation']['messages']['MANDATORY_DATE'] validate_with = [DateRequired(message=date_messages['MANDATORY_DATE'])] if 'validation' in answer and 'messages' in answer['validation'] \ and 'INVALID_DATE' in answer['validation']['messages']: date_messages['INVALID_DATE'] = answer['validation']['messages']['INVALID_DATE'] validate_with += [DateCheck(date_messages['INVALID_DATE'])] # Set up all the calendar month choices for select month_choices = [('', 'Select month')] + [(str(x), calendar.month_name[x]) for x in range(1, 13)] DateForm.month = SelectField(choices=month_choices, default='', validators=validate_with) return DateForm
def get_month_year_form(answer, error_messages): """ Returns a month year form metaclass with appropriate validators. Used in both date and date range form creation. :param answer: The answer on which to base this form :param error_messages: The messages to use upon this form during validation :return: The generated MonthYearDateForm metaclass """ class MonthYearDateForm(Form): year = StringField() validate_with = [OptionalForm()] if answer['mandatory'] is True: error_message = error_messages['MANDATORY_DATE'] if 'validation' in answer and 'messages' in answer['validation'] \ and 'MANDATORY_DATE' in answer['validation']['messages']: error_message = answer['validation']['messages']['MANDATORY_DATE'] validate_with = [DateRequired(message=error_message)] if 'validation' in answer and 'messages' in answer['validation'] \ and 'INVALID_DATE' in answer['validation']['messages']: error_message = answer['validation']['messages']['INVALID_DATE'] validate_with += [MonthYearCheck(error_message)] else: validate_with += [MonthYearCheck()] # Set up all the calendar month choices for select month_choices = [('', 'Select month')] + [(str(x), calendar.month_name[x]) for x in range(1, 13)] MonthYearDateForm.month = SelectField(choices=month_choices, default='', validators=validate_with) return MonthYearDateForm
def _monthToInt( month ): months = {m.lower(): idx for idx, m in enumerate(calendar.month_name)} try: return months[month.lower()] except: return -1
def dateFormatter(self, date): month = calendar.month_name[date.month] weekday = calendar.day_name[date.weekday()] day = date.day year = date.year results = str(weekday) + ", " + str(month) + " " + str(day) + ", " + str(year) return results
def month_name(no_month): if isinstance(no_month, datetime): no_month = no_month.month return calendar.month_name[no_month]
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 standardize_act_target(tgt_url): ''' Produce label for identified Act target based on URL. This is cleaner than pulling the text and accounting for typos and inconsistencies.''' surl = tgt_url.split("/") date = surl[3].split("-") date = "{} {}, {}".format(calendar.month_name[int(date[1])], date[2], date[0]) try: tgt_title = "Act of {}, ch. {} {}".format(date, surl[4].strip("ch"), surl[5].strip("s")) except: try: if "ch" in surl[4]: tgt_title = "Act of {}, ch. {}".format(date, surl[4].strip("ch")) elif "s" in surl[4]: tgt_title = "Act of {}, {}".format(date, surl[4].strip("s")) except: tgt_title = "Act of {}".format(date) try: surl[4] = surl[4].lstrip("ch") except: pass try: surl[5] = surl[5].lstrip("s") except: pass tgt_url = "/".join(x for x in surl) try: tgt_url_broad = "/".join(tgt_url.split("/")[0:6]) except: tgt_url_broad = "/".join(tgt_url.split("/")[0:5]) return tgt_title, tgt_url, tgt_url_broad