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


Python calendar.Calendar类代码示例

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


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

示例1: events_source_in_week

    def events_source_in_week(self, request, pk, format=None):
        """
        Lista todos los eventos de la semana en la que nos encontramos
        :param request:
        :param pk:
        :param format:
        :return:
        """

        _pk = 0
        list_week = []
        list_events_week = []
        calendary = Calendar(0)
        today = timezone.localtime(timezone.now())
        year = today.year
        month = today.month
        events_in_week = 0

        if type(pk) is DictType:
            _pk = pk['pk']
            list_week = pk['list_week']
            month = pk['month']
            year = pk['year']
            events_in_week = pk['events_db']
        else:
            _pk = pk
            for it in calendary.monthdayscalendar(today.year, today.month):
                try:
                    if it.index(today.day):
                        list_week = it
                except ValueError:
                    pass

        if not events_in_week:
            try:
                events_in_week = Events.objects.filter(ID_Source=_pk)
            except Events.DoesNotExist:
                return HttpResponse(status=404)

        if request.method == 'GET':

            for it in list_week:
                if not it == 0:
                    dict_day = {'day': it, 'pk': _pk, 'year': year, 'month': month, 'events_db': events_in_week}
                    list_events_week.append(EventsInformation().events_source_in_day(request, dict_day))

            result = []  # Esta lista es para el uso interno de las otras funciones de la clase
            result_json = []  # Esta lista es para dar más información al json de la api
            count = 0
            for it in list_events_week:
                count += 1
                result_json.append({'day_week': count, 'events': it})
                for it_dict in it:
                    if it_dict:
                        result.append(it_dict)

            if type(pk) is DictType:
                return result
            else:
                return JSONResponse(result_json)
开发者ID:MGautier,项目名称:security-sensor,代码行数:60,代码来源:views.py

示例2: generate_random

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,代码行数:30,代码来源:testlogger.py

示例3: render

    def render(self, context):
        mycal = Calendar()
        context[self.var_name] = mycal.monthdatescalendar(
            int(self.year.resolve(context)), int(self.month.resolve(context))
        )

        return ""
开发者ID:emlprime,项目名称:rcs,代码行数:7,代码来源:filters.py

示例4: create_calendar_table

 def create_calendar_table(self):
     self.calendar_layout.clear_widgets()
     calendars = Calendar()
     calendars.setfirstweekday(calendar.SUNDAY)
     selected_month = self.month - 1
     year_dates = calendars.yeardays2calendar(year=self.year, width=1)
     th1 = KV.invoice_tr(0, 'Su')
     th2 = KV.invoice_tr(0, 'Mo')
     th3 = KV.invoice_tr(0, 'Tu')
     th4 = KV.invoice_tr(0, 'We')
     th5 = KV.invoice_tr(0, 'Th')
     th6 = KV.invoice_tr(0, 'Fr')
     th7 = KV.invoice_tr(0, 'Sa')
     self.calendar_layout.add_widget(Builder.load_string(th1))
     self.calendar_layout.add_widget(Builder.load_string(th2))
     self.calendar_layout.add_widget(Builder.load_string(th3))
     self.calendar_layout.add_widget(Builder.load_string(th4))
     self.calendar_layout.add_widget(Builder.load_string(th5))
     self.calendar_layout.add_widget(Builder.load_string(th6))
     self.calendar_layout.add_widget(Builder.load_string(th7))
     if year_dates[selected_month]:
         for month in year_dates[selected_month]:
             for week in month:
                 for day in week:
                     if day[0] > 0:
                         item = Factory.CalendarButton(text="[b]{}[/b]".format(day[0]))
                     else:
                         item = Factory.CalendarButton(disabled=True)
                     self.calendar_layout.add_widget(item)
开发者ID:eyelevate,项目名称:jayscleaners-py,代码行数:29,代码来源:calender_generator.py

示例5: get_month_events

def get_month_events(year, month):
    # Get the day-dates of the current month
    cal = Calendar(0) # default replace by user db? (starting day)
    the_month = cal.monthdatescalendar(year, month)

    # First day of first week
    begin = the_month[0][0]
    # Last day of last week
    end = the_month[-1][-1]
    events = Event.query.filter(
        Event.event_date > begin.strftime('%Y-%m-%d'),
        Event.event_date < end.strftime('%Y-%m-%d')) \
        .options(lazyload('creator')).all()

    # Load the days for the calendar
    def per_day(day):
        # Get the interval bounds of that day
        day_start = datetime.combine(day, time())
        day_end = day_start + timedelta(days = 1)
        # Run through all events
        day_events = []
        for e in events:
            if e.event_date >= day_start and e.event_date < day_end:
                day_events.append(e)
        return (day, day_events)
    def per_week(week):
        return [per_day(d) for d in week]
    def per_month(month):
        return [per_week(w) for w in month]

    return per_month(the_month)
开发者ID:alexd2580,项目名称:evelyn,代码行数:31,代码来源:views.py

示例6: _get_month_nth_weekday

    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,代码行数:27,代码来源:academy_training_session_wizard.py

示例7: get_week_count

def get_week_count(firstdayofweek, firstweekofyear, year, month, day):
	cl = Calendar(firstdayofweek)
	data = cl.monthdayscalendar(year, 1)
	week_cnt = 0
	day_cnt = 0
	# counting for first month
	for i in range(0, 7):
		if data[0][i] != 0:
			day_cnt += 1
	if (firstweekofyear == 2 and day_cnt < 4) or (firstweekofyear == 3 and day_cnt < 7):
		week_cnt = -1
	if month != 1:		
		week_cnt += len(data)
		if data[len(data)-1][6] == 0:
			week_cnt -= 1
		#counting for other monthes
		for m in range(2, month):
			data = cl.monthdayscalendar(year, m)
			week_cnt += len(data)
			if data[len(data)-1][6] == 0:
				week_cnt -= 1
	#here we have week count in week_cnt before current month
	data = cl.monthdayscalendar(year, month)	
	for week in range(0, len(data)):
		week_cnt += 1
		if day in data[week]:
			break
	return week_cnt
开发者ID:VDOMBoxGroup,项目名称:vdomserver1.3,代码行数:28,代码来源:chronology.py

示例8: get_context_data

    def get_context_data(self, **kwargs):
        data = super(BaseCalendarMonthArchiveView, self).get_context_data(**kwargs)
        date = data['date_list'][0]
        
        cal = Calendar(self.get_first_of_week())

        month_calendar = []
        now = datetime.datetime.utcnow()
        
        date_lists = defaultdict(list)
        
        for obj in data['object_list']:
            obj_date = getattr(obj, self.get_date_field())            
            try:
                obj_date = obj_date.date()
            except AttributeError:
                # It's a date rather than datetime, so we use it as is
                pass                    
            date_lists[obj_date].append(obj)

        for week in cal.monthdatescalendar(date.year, date.month):
            week_calendar = []
            for day in week:
                week_calendar.append({
                    'day': day,
                    'object_list': date_lists[day],
                    'today': day == now.date(),
                    'is_current_month': day.month == date.month,
                })
            month_calendar.append(week_calendar)
            
        data['calendar'] = month_calendar

        return data
开发者ID:AdrianRibao,项目名称:django-extra-views,代码行数:34,代码来源:dates.py

示例9: month_sales

	def month_sales(self,farm):
		'''This function returns the monthly sales'''
		date = datetime.date.today()
		cal = Calendar()
		days_month=list(set(list(cal.itermonthdays(date.year, date.month)))-set([0]))
		orders = PurchaseOrder.objects.filter(farm=farm,date__month=date.month,date__year=date.year)
		products=PurchaseOrder.objects.product_order_month(farm,date)
		total_day=[]
		count_sales=[]
		for day in days_month:
			total_day.append(0)
			count_sales.append(0)
		total_month=0
		total_products = PurchaseOrder.objects.count_products_month(farm,date)
		for order in orders:
			for idx,day in enumerate(days_month):
				if order.date.day==day:
					total = order.total_order
					t_products = order.quantity
					if total_day[idx]!=0:
						price  = total_day[idx]+total
						total_day[idx]=price
						total_month+=total
						count = count_sales[idx]
						count_sales[idx]=(count+t_products)
					else:
						total_month+=total
						total_day[idx]=total
						count_sales[idx]=(t_products)

					break
		data = {'labels':days_month, 'values':total_day, 'count':count_sales, 'total_month':total_month, 'total_products':total_products, 'products':products}
		return data
开发者ID:aramakao,项目名称:ceres,代码行数:33,代码来源:models.py

示例10: week_sales

	def week_sales(self,farm):
		'''This function returns the weekly deals'''
		date = datetime.date.today()
		orders = PurchaseOrder.objects.order_week(farm=farm,date=date)
		products_order=PurchaseOrder.objects.product_order_week(farm=farm,orders=orders)
		total_products = products_order[0]['total']
		products = products_order[1]
		sales_day=[]
		count_sales=[]
		total_day=0
		cal = Calendar()
		days = list(cal.iterweekdays())
		for day in days:
			sales_day.append(0)
			count_sales.append(0)
		for order in orders:
			order_day=order.date.isocalendar()[2]
			total = order.total_order
			t_products = order.quantity
			for day in days:
				if day==order_day:
					if sales_day[day]!=0:
						price  = sales_day[day]+total
						sales_day[day]=price
						total_day+=total
						count = count_sales[day]
						count_sales[day]=(count+t_products)
					else:
						total_day+=total
						sales_day[day]=total_day
						count_sales[day]=(t_products)
					break
		data = {'values':sales_day, 'count':count_sales, 'total_day':total_day, 'total_products':total_products, 'products':products}
		return data
开发者ID:aramakao,项目名称:ceres,代码行数:34,代码来源:models.py

示例11: meetup_day

def meetup_day(year, month, name, ordinal):
    
    wkday_dict = {'Monday':0, 'Tuesday':1,
                  'Wednesday':2, 'Thursday':3,
                  'Friday':4, 'Saturday':5, 
                  'Sunday':6
                  }
    wkday = wkday_dict[name]
    
    cal = Calendar()
    date_list = []
    
    for day_date, weekday in cal.itermonthdays2(year, month):
        if weekday == wkday and not day_date == 0:
            date_list.append(day_date)
    
    date_dict = {'1st':0, '2nd':1, '3rd':2, '4th':3, '5th':4}
    if ordinal in date_dict:
        day = date_list[date_dict[ordinal]]
    elif ordinal == 'teenth':
        for day_date in date_list:
            if 12 < day_date < 20:
                day = day_date
    elif ordinal == 'last':
        day = date_list[-1]
                    
    
    return date(year, month, day)
开发者ID:bryjcannon,项目名称:exercism,代码行数:28,代码来源:meetup.py

示例12: get_last_day_of_month

def get_last_day_of_month(year, month, day):
    month_list = Calendar().monthdatescalendar(year, month)
    month_list.reverse()
    for week in month_list:
        if week[day].month==month:
            return week[day]
    return None
开发者ID:christianhans,项目名称:mensafeed,代码行数:7,代码来源:utils.py

示例13: render_month

    def render_month (self, x,y, month_no):
        svg = ''        
    
        svg += '<g>'
        svg += '<text x="%smm" y="%smm" font-family="\'%s\'" font-size="%smm" text-anchor="middle" fill="%s">'% (x + self.style['month-width']/2,y+self.style['month-padding-top'], self.style['month-font-family'], self.style['month-font-size'], self.style['month-color'])
        svg += '%s' % (self.month_names [month_no-1])
        svg += '</text>'
        svg += self.render_week (x, y+self.style['week-padding-top'])
        
        day_of_week = -1 # will start from Monday
        week_no = 0        

        c = Calendar (0)        
        for day_no in c.itermonthdays (self.year, month_no):

            day_of_week = (day_of_week + 1) % 7
            if day_of_week == 0: week_no += 1
            
            if day_no == 0: continue # month not yet started
            
            xx = x + self.style['day-width'] * (day_of_week)
            yy = y + self.style['day-padding-top'] + week_no * self.style['day-height']
            
            svg += self.render_day (xx, yy, month_no, day_no, day_of_week)
        
        svg += '</g>'
        return svg
开发者ID:mr-bin,项目名称:scripts,代码行数:27,代码来源:svg_calendar.py

示例14: m_to_expiry

 def m_to_expiry(self, m_expiry):
     c = Calendar()
     expiry = datetime.strptime(m_expiry, '%Y%m%d')
     mdc = c.monthdatescalendar(expiry.year, expiry.month)
     fridays = [x[4] for x in mdc if x[4].month == expiry.month]
     if fridays[2] == expiry.date(): expiry += timedelta(days=1)        
     return expiry.strftime('%y%m%d')
开发者ID:gazzman,项目名称:ib,代码行数:7,代码来源:reversal_feed_analyzer.py

示例15: get_business_days_quantity

def get_business_days_quantity(limit_day = 31):
    """
    Retorna quatidade de dias úteis no mês.
    """
    args = get_args()
    businessdays = 0
    calendar = Calendar()

    for week in calendar.monthdayscalendar(args.year, args.month):
        for i, day in enumerate(week):

            if day == 0 or i >= 5:
                continue

            for holiday in HOLIDAYS:
                if holiday['month'] == args.month and holiday['day'] == day:
                    businessdays -= 1
                    continue

            businessdays += 1

            if (int(day) == int(limit_day)):
                return businessdays

    return businessdays
开发者ID:alexandretaz,项目名称:dimep,代码行数:25,代码来源:dimep.py


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