python类month_name()的实例源码

views.py 文件源码 项目:django-danceschool 作者: django-danceschool 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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)
views.py 文件源码 项目:django-danceschool 作者: django-danceschool 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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)
admin.py 文件源码 项目:django-danceschool 作者: django-danceschool 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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
app.py 文件源码 项目:bday-app 作者: pybites 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
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)
constants.py 文件源码 项目:gae-sports-data 作者: jnguyen-ca 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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
test_date_filters.py 文件源码 项目:ussd_airflow 作者: mwaaas 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
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
        )
views.py 文件源码 项目:thunderingplains 作者: lyctc 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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}
test_dashboard.py 文件源码 项目:vnchart 作者: invkrh 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def test_month_name(self):
        import calendar
        m = datetime.now().month
        expected = calendar.month_name[m]
        result = month_name()
        self.assertEqual(expected, result)
test_dashboard.py 文件源码 项目:vnchart 作者: invkrh 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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)
_strptime.py 文件源码 项目:kinect-2-libras 作者: inessadl 项目源码 文件源码 阅读 42 收藏 0 点赞 0 评论 0
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
models.py 文件源码 项目:dprr-django 作者: kingsdigitallab 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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
_strptime.py 文件源码 项目:hostapd-mana 作者: adde88 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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
Chains.py 文件源码 项目:chains 作者: hc-12 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 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)
_strptime.py 文件源码 项目:Intranet-Penetration 作者: yuxiaokui 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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
periods.py 文件源码 项目:wagtail_room_booking 作者: Tamriel 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def name(self):
        return standardlib_calendar.month_name[self.start.month]
_strptime.py 文件源码 项目:MKFQ 作者: maojingios 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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
test_month_setbuilder.py 文件源码 项目:aws-ops-automator 作者: awslabs 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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})
soup.py 文件源码 项目:TimeplanSoup 作者: Piees 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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
allSoupQL.py 文件源码 项目:TimeplanSoup 作者: Piees 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
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
allSoup.py 文件源码 项目:TimeplanSoup 作者: Piees 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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
helper.py 文件源码 项目:TestRewrite 作者: osqa-interns 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
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]
_strptime.py 文件源码 项目:zippy 作者: securesystemslab 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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
_strptime.py 文件源码 项目:oil 作者: oilshell 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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
_strptime.py 文件源码 项目:python2-tracer 作者: extremecoders-re 项目源码 文件源码 阅读 39 收藏 0 点赞 0 评论 0
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
stats.py 文件源码 项目:django-danceschool 作者: django-danceschool 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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)
stats.py 文件源码 项目:django-danceschool 作者: django-danceschool 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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
views.py 文件源码 项目:django-danceschool 作者: django-danceschool 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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
models.py 文件源码 项目:django-danceschool 作者: django-danceschool 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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]]
models.py 文件源码 项目:django-danceschool 作者: django-danceschool 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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])
models.py 文件源码 项目:django-danceschool 作者: django-danceschool 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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'))


问题


面经


文章

微信
公众号

扫码关注公众号