当前位置: 首页>>代码示例>>Python>>正文


Python Calendar.itermonthdates方法代码示例

本文整理汇总了Python中calendar.Calendar.itermonthdates方法的典型用法代码示例。如果您正苦于以下问题:Python Calendar.itermonthdates方法的具体用法?Python Calendar.itermonthdates怎么用?Python Calendar.itermonthdates使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在calendar.Calendar的用法示例。


在下文中一共展示了Calendar.itermonthdates方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _get_month_nth_weekday

# 需要导入模块: from calendar import Calendar [as 别名]
# 或者: from calendar.Calendar import itermonthdates [as 别名]
    def _get_month_nth_weekday(self, in_date):
        """ Returns ZERO based nth date in month which weekday is the same
        as given (First monday, first sunday, second sunday etc...)

        @param in_date (date): random date in month
        @param weekday (int) : weekday index (0 --> Monday, ..., 6 --> Sunday)
        @param nth (int)     : number of weekday match (-1 --> Last, 0 --> First,...)
        """

        cal = Calendar(firstweekday=0)

        weekday = self._get_choosen_weekday()
        nth = self._get_choosen_weekday_position()

        month = in_date.month
        datelist = cal.itermonthdates(in_date.year, month)

        msg = 'nth ({}) param can not be less than -1 in _get_month_nth_weekday'
        assert nth >= -1, msg.format(nth)


        valid = [
            item for item in datelist \
            if item.weekday() == weekday and item.month == month
        ]

        return valid[nth] if len(valid) >= nth else None
开发者ID:sotogarcia,项目名称:odoo-academy,代码行数:29,代码来源:academy_training_session_wizard.py

示例2: generate_random

# 需要导入模块: from calendar import Calendar [as 别名]
# 或者: from calendar.Calendar import itermonthdates [as 别名]
def generate_random():
    'Generates a years worth of random logs.'

    p = path('c:\\test')

    words = 'foo bar to be or not the and apple orange banana cherry futon proleptic gregorian ordinal'.split()

    cal = Calendar()

    for month in xrange(1, 12):
        for day in cal.itermonthdates(2007, month):

            messages = []
            for x in xrange(2, randrange(20, 50)):
                shuffle(words)

                messages.append(
                    S(buddy     = S(name = 'digsby0%d' % randrange(1, 3)),
                      timestamp = random_time_in_day(day),
                      message   = ' '.join(words[:randrange(1, len(words)+1)])))

            messages.sort(key = lambda mobj: mobj['timestamp'])

            daylog = p / (day.isoformat() + '.html')

            with daylog.open('w') as f:
                f.write(html_header % dict(title = 'IM Logs with %s on %s' % ('digsby0%d' % randrange(1, 3), day.isoformat())))

                for mobj in messages:
                    f.write(generate_output_html(mobj))
开发者ID:AlexUlrich,项目名称:digsby,代码行数:32,代码来源:testlogger.py

示例3: sick

# 需要导入模块: from calendar import Calendar [as 别名]
# 或者: from calendar.Calendar import itermonthdates [as 别名]
def sick(request,user_id):
    users = User.objects.all()
    selected = User.objects.get(pk=user_id)
    user_days = Day.objects.filter_user(user_id)

    year_form = YearChangeForm({'year':request.session.get('year',2013)})
    year = int(request.session.get('year',2013))

    cal = MikranCalendar(user_days,year)

    if request.method == 'POST': # If the form has been submitted...
        form = SickForm(user=request.user, data=dict(request.POST.items() + {'user_id':selected.id}.items())) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            start_date = datetime.date(int(request.POST['first_day_year']),
                                       int(request.POST['first_day_month']),
                                       int(request.POST['first_day_day']))
            
            end_date = datetime.date(int(request.POST['last_day_year']),
                                     int(request.POST['last_day_month']),
                                     int(request.POST['last_day_day']))

            start_month = int(request.POST['first_day_month'])
            end_month = int(request.POST['last_day_month'])

            status_obj = Status.objects.get(status=form.translateChoice(request.POST['status']));

            days = []
            current = Calendar()
            for month in range(start_month,end_month+1):
                for day in current.itermonthdates(int(request.POST['first_day_year']),month):
                    if day >= start_date and day <= end_date:
                        if day.isoweekday() < 6:
                            if not day in days:
                                if not day.strftime("%02d-%02m-%04Y") in cal.get_free_days(year):
                                    days.append(day)

            #build list of objects for bulk create
            Day.objects.bulk_create([Day(user_id=selected.id,status_id=status_obj.id,leave_date=day) for day in days])
            #send bulk sick days create signal
            days_planned.send(sender=User, user=selected, status=status_obj, start=start_date, end=end_date, operation="SICK".encode('utf-8'))

            #display OK message for the user
            messages.add_message(request,messages.INFO, 'Zgłosiłeś zwolnienie lekarskie od %s do %s' %(start_date,end_date))

            return HttpResponseRedirect(reverse('leave.views.show_user',args=(selected.id,)))
    else:
        form = SickForm()
        
    return render_to_response('sick_days.html',{'users': users,
                                                'selected':selected,
                                                'user_days':user_days,
                                                'cal':mark_safe(cal.formatyear(year,4)),
                                                'year_form':year_form,
                                                'days_present': user_days.filter_present().count(),
                                                'days_sick':user_days.filter_sick().count(),
                                                'days_planned':user_days.filter_planned().count(),
                                                'days_accepted':user_days.filter_accepted().count(),
                                                'form':form},
                              context_instance=RequestContext(request))
开发者ID:zdanozdan,项目名称:leave,代码行数:61,代码来源:views.py

示例4: get_context_data

# 需要导入模块: from calendar import Calendar [as 别名]
# 或者: from calendar.Calendar import itermonthdates [as 别名]
    def get_context_data(self, **kwargs):

        def get_weekday_text(athlete, weekday):
            morph = pymorphy2.MorphAnalyzer()
            if athlete.week_day:
                for week_day in eval(athlete.week_day):
                    if weekday < int(week_day):
                        day_text = morph.parse(Athlete.WEEK_DAYS[int(week_day)][1])[0].inflect({'accs'}).word
                        return 'во' if Athlete.WEEK_DAYS[int(week_day)][0] == 1 else 'в', day_text
                day_text = morph.parse(Athlete.WEEK_DAYS[int(eval(athlete.week_day)[0])][1])[0].inflect({'accs'}).word
                return 'во' if Athlete.WEEK_DAYS[int(eval(athlete.week_day)[0])][0] == 1 else 'в', day_text
            return 'не', 'запланирована'

        athlete = Athlete.objects.get_or_create(user=self.request.user)[0]
        today = datetime.now().date()
        cal = Calendar(MONDAY)
        year = int(self.kwargs.get('year'))
        month = int(self.kwargs.get('month'))
        day = int(self.kwargs.get('day'))
        current_date = date(year, month, day)
        next_month = add_months(current_date, 1)
        prev_month = sub_months(current_date, 1)
        month_dates = list(cal.itermonthdates(year, month))
        trainings = Training.objects.filter(
            date__in=month_dates,
            workout_diary=self.object
        )
        month_dates_with_training = [
            (item, True) if athlete.week_day and item >= today
            and str(item.weekday()) in athlete.week_day
            else (item, trainings.filter(date=item).last())
            for item in month_dates
        ]
        splited = chunks(month_dates_with_training, 7)
        month = [(week[0][0].isocalendar()[1] == today.isocalendar()[1], week) for week in splited]
        training_today = athlete.week_day and (str(today.weekday()) in athlete.week_day)
        training = get_training(self.request.user, current_date)
        ctx = {
            'training': training,
            'today': today,
            'month': month,
            'prev_month': prev_month,
            'next_month': next_month,
            'current_month': month_text(current_date.month),
            'current_date': current_date,
            'current_weekday': Athlete.WEEK_DAYS[current_date.weekday()][1],
            'training_duration': athlete.get_training_duration_display(),
            'history': current_date < today,
            'training_today': training_today,
            'button_text': (True, 'Начать тренировку')
            if training_today else
            (False, 'Следующая тренировка %s %s' % get_weekday_text(athlete=athlete, weekday=today.weekday()))
        }
        return ctx
开发者ID:andruwwwka,项目名称:super5,代码行数:56,代码来源:views.py

示例5: reminders_calendar

# 需要导入模块: from calendar import Calendar [as 别名]
# 或者: from calendar.Calendar import itermonthdates [as 别名]
def reminders_calendar(request, year=datetime.now().year, month=datetime.now().month):
    """Show a calendar of all reminders for a user"""
    month = int(month)
    year = int(year)
    months = get_months()
    today = datetime.now().date()

    # Set a set of year between now and 20 years in the future
    years = [x for x in range(datetime.now().year, datetime.now().year + 20)]
    # Get the selected month
    m = months[str(month)]
    # Create a calendar starting with Sunday from the last month
    cal = Calendar(SUNDAY)
    # Get all the days in the calendar month and year specified
    days = [day for day in cal.itermonthdates(year, month)]
    # Group the days into weeks going from Sunday to Saturday
    weeks = [days[i * 7:(i + 1) * 7] for i in range((len(days) / 7 + 1))]
    # Find the next and previous months
    next_month, previous_month = get_next_and_previous(year, month)

    # Get all of the reminders that happen in the current month
    reminders = Reminder.objects.filter(user=request.user, sent=False)
    reminder_dates = [reminder.date.date() for reminder in reminders
                      if reminder.date.date().month == month]

    if request.method == 'POST':
        selected_month = request.POST.get('month')
        selected_year = request.POST.get('year')
        return redirect('calendar-date', year=selected_year, month=selected_month)

    context = {
        'weeks': weeks,
        'months': months,
        'today': today,
        'm': m,
        'year': year,
        'years': years,
        'next_month': next_month,
        'previous_month': previous_month,
        'reminders': reminders,
        'reminder_dates': reminder_dates,
    }
    return render(request, 'reminders/calendar.html', context)
开发者ID:dansackett,项目名称:mydash,代码行数:45,代码来源:views.py

示例6: initialize_month_attendance

# 需要导入模块: from calendar import Calendar [as 别名]
# 或者: from calendar.Calendar import itermonthdates [as 别名]
def initialize_month_attendance(**kwargs):    
    print 'initializing month_attendance'
    latest = ServiceReport.objects.latest('month').month
    year = kwargs['year'] if kwargs.has_key('year') else latest.strftime('%Y')
    month = kwargs['month'] if kwargs.has_key('month') else latest.strftime('%m')
    initial = []
    mwlist = []
    welist = []
    cal = Calendar()
    for day in cal.itermonthdates(int(year),int(month)):
        print 'day: %s' % day.isoformat()
        meeting = None
        if day.weekday()==settings.MEETING_MIDWEEK:
            meeting = "MW"
            mwlist.append({'meeting': meeting, 'meeting_date': day})
        if day.weekday()==settings.MEETING_WEEKEND:
            meeting = "WE"
            welist.append({'meeting': meeting, 'meeting_date': day})
        initial = mwlist + welist
    return initial
开发者ID:abdallah,项目名称:secretary-briefcase,代码行数:22,代码来源:views.py

示例7: calendario_mes

# 需要导入模块: from calendar import Calendar [as 别名]
# 或者: from calendar.Calendar import itermonthdates [as 别名]
def calendario_mes(request,curso_id,ano,mes):
    ano = int(ano)
    mes = int(mes)
    cal = HTMLCalendar()
    
    
    dias_semana = []
    curso = Curso.objects.get(id=curso_id)
    for clase in curso.clase_set.all():
        dias_semana.append(clase.dia_semana-1)
    dias_clase = []
    
    
    c = Calendar()
    for d in c.itermonthdates(ano,mes):
        ##print d
        if d.weekday() in dias_semana:
            #evitamos recibir los dias que no son del mes que toca
            if d.month == mes:
                dias_clase.append(d.day)
            
    cal = ClasesCalendar(dias_clase)
    calendario = cal.formatmonth(ano,mes)
    return render_to_response('cursos/mes.html', {'calendario': calendario, "ano": ano, "mes": mes})
开发者ID:Etxea,项目名称:gestion_eide_web,代码行数:26,代码来源:views.py

示例8: _get_date_list

# 需要导入模块: from calendar import Calendar [as 别名]
# 或者: from calendar.Calendar import itermonthdates [as 别名]
 def _get_date_list(self):
     _cal = Calendar(5)
     _date = list(_cal.itermonthdates(self._context.get('rpt_year'), self._context.get('rpt_month')))
     return _date
开发者ID:sajinaziz,项目名称:cicon_addons_9,代码行数:6,代码来源:pm_plan_report.py

示例9: consumed_hours

# 需要导入模块: from calendar import Calendar [as 别名]
# 或者: from calendar.Calendar import itermonthdates [as 别名]
from datetime import datetime

now = datetime.now()
year, month = now.year, now.month

from calendar import Calendar

def consumed_hours():
    from numpy.random import normal
    return round(normal(10.5, 0.7), 1)

cal = Calendar()
for d in cal.itermonthdates(year, month):
    if d.month != month:
        print '%5s'%('%d/%d'%(d.month, d.day)),
    else:
        print '%5d'%d.day,

    if d.weekday() >= 6:
        print

        print ' '.join(['%5.1f'%consumed_hours() for _ in range(5)]),
        print ' '.join(['%5s'%'-' for _ in range(2)])

        print '-'*42
开发者ID:ayokyun,项目名称:si-epm-timetable,代码行数:27,代码来源:random_timetable.py


注:本文中的calendar.Calendar.itermonthdates方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。