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
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)
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
def GetRecord(self, year, month): ''' mode: 获得year年month月的数据 ''' result = {} calendar = Calendar(firstweekday=7) now_time = time.localtime() now_year = now_time.tm_year now_month = now_time.tm_mon now_month_day = now_time.tm_mday all_week = calendar.monthdayscalendar(year= year, month=month) #print(all_week) for week in all_week: if 0 in week:#清空日期为0的 while 0 in week: week.remove(0) #将日期格式转化为目标格式 for day in week: if year >= now_year and month >= now_month and day > now_month_day: return result day_str = "%d-%02d-%02d"%(year, month, day) if day_str in self.record: result["%d月%d日"%(month, day)] = self.record[day_str] else: result["%d月%d日"%(month, day)] = 0 return result
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
def get_cal(country): n = datetime.now() cal = Calendar() month_cal = cal.monthdayscalendar(n.year, n.month) if country == 'Fr': day_list = WEEKDAYS_FR else: day_list = WEEKDAYS return month_cal, day_list
def calendarSite(year, month): cal = Calendar() weeks = cal.monthdayscalendar(year = year, month = month) for week in weeks: for i in range(0, len(week)): if week[i] == 0: week[i] = "" return {'year': year, 'month': months[month-1] ,'dayNames' : dayNames, 'weeks' : weeks}
def meetup_day(year, month, day_of_the_week, which): cal = Calendar() daynum = WEEKDAY_TO_NUMBER[day_of_the_week] last_days = [] for weekday in cal.monthdayscalendar(year, month): if which in DESCRIPTOR.keys() and weekday[daynum] > DESCRIPTOR[which]: return date(year, month, weekday[daynum]) # meetup_date = date(year, month, weekday[daynum]) if which == "last" and weekday[daynum] > 20: last_days.append(weekday[daynum]) return date(year, month, max(last_days))
def get_first_weekdays(year, month): """ input : year=2021, month=4 output: [(1, 3), (2, 4), (3, 5), (4, 6), (5, 0), (6, 1), (7, 2)] : means [(2021/04/01, 3(Thu)), (2021/04/02, 4(Fri)), .., (2021/04/07, 2(Wed)] """ from calendar import Calendar cal = Calendar() first_week = cal.monthdayscalendar(year, month)[0] wd_1st = first_week.index(1) first_weekdays = [] for d in range(1, 8): first_weekdays.append((d, (wd_1st + d - 1)%7)) return first_weekdays
def events_source_in_month(self, request, pk, format=None): """ Lista todos los eventos de una source en el mes actual :param request: :param pk: :param format: :return: """ list_events_month = [] calendary = Calendar(0) today = timezone.localtime(timezone.now()) year = today.year month = today.month events_in_month = 0 if type(pk) is DictType: _pk = pk['pk'] list_month = pk['list_month'] month = pk['month'] year = pk['year'] events_in_month = pk['events_db'] else: _pk = pk list_month = calendary.monthdayscalendar(today.year, today.month) if not events_in_month: try: events_in_month = Events.objects.filter(ID_Source=_pk) except Events.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': for it in list_month: dict_month = {'pk': _pk, 'list_week': it, 'year': year, 'month': month, 'events_db': events_in_month} list_events_month.append(EventsInformation().events_source_in_week(request, dict_month)) result = [] count = 0 for it in list_events_month: count += 1 result.append({'week': count, 'days': it}) if type(pk) is DictType: return result else: return JSONResponse(result)
def get_calendar(professor, month=6): """ get calendar for given month :return: """ now = datetime.datetime.now().date().replace(month=month) events = ProfessorDay.objects.filter(professor=professor) calendar = Calendar(0) weeks = calendar.monthdayscalendar(month=month, year=now.year) days = dict( map(lambda entry: (entry.date.day, {'date': entry.date, 'available': entry.available, 'exam': entry.exam_group} ), events) ) weeks = map(lambda week: map(lambda day: days[day] if day in days else {}, week), weeks) return weeks
def post_count_possible(self,period=None): if period == 'week': calendar_week = range_of_date_week(date.today()) interval = (calendar_week[0], calendar_week[-1]) completed = jmodels.Entry.objects.filter(user__username=self.username,date__range=interval).count() total_possible = 7 return "Completed %s out of the %s possible journal entries this week" % (completed, total_possible) elif period == 'month': c = Calendar(0) weeks = c.monthdayscalendar(date.today().year,date.today().month) max_days = 1 for w in weeks: max_days = max(w) completed = jmodels.Entry.objects.filter(user__username=self.username,date__year=date.today().year,date__month=date.today().month).count() total_possible = max_days return "Completed %s out of the %s possible journal entries this month" % (completed, total_possible) else: completed = jmodels.Entry.objects.filter(user__username=self.username).count() total_possible = (date.today() - self.profile.user.date_joined.date()).days + 4 return "Completed %s out of the %s possible entries since you started journaling on Emovolution." % (completed, total_possible)
class Meetup: def __init__(self, year, month, week_day): self.calendar = Calendar() self.week_day = week_day self.month_to_list = self.calendar.monthdayscalendar(year, month) @property def get_all_week_days(self): index = list(day_name).index(self.week_day) all_week = [l[index] for l in self.month_to_list] return list(filter(lambda x: x > 0, all_week)) def get_nth(self, counter): week_days = self.get_all_week_days try: return week_days[counter - 1] except IndexError: raise MeetupException def get_teenth(self): return next(filter(lambda x: x >= 10, self.get_all_week_days))
def print_birthdays(year: int = None): if year is None: year = datetime.today().year # Make Sunday the first day of the week (Saturday becomes the 7th day). # If a member has a birthday on Sunday, we want to move it to the next week. # We're doing this only for indentation and compartmentalization purposes. cal = Calendar(firstweekday=6) for month in range(1, 13): month_weeks: List[List[int]] = cal.monthdayscalendar(year, month) members = get_members_by_birth_month(month) print(f'Birthdays for {month_to_name[month]}') for week_ind, week in enumerate( group_birthday_members_by_weeks(members, month_weeks)): for member in week: member_info = f'{member.full_name()}, {member.birth_date.strftime("%d.%m.%Y")} - {member.years_old(year)} years' if week_ind % 2 == 0: print(f' {member_info}') else: print(member_info) print()
def image(self, user, width, height): """Generates an image with a calendar view.""" # Show a calendar relative to the current date. try: time = self._local_time.now(user) except DataError as e: raise ContentError(e) # Get the number of events per day from the API. event_counts = self._event_counts(time, user) # Create a blank image. image = Image.new(mode='RGB', size=(width, height), color=BACKGROUND_COLOR) draw = Draw(image) # Get this month's calendar. try: firstweekday = WEEK_DAYS[user.get('first_week_day')] except KeyError: firstweekday = SUNDAY calendar = Calendar(firstweekday=firstweekday) weeks = calendar.monthdayscalendar(time.year, time.month) # Determine the spacing of the days in the image. x_stride = width // (DAYS_IN_WEEK + 1) y_stride = height // (len(weeks) + 1) # Draw each week in a row. for week_index in range(len(weeks)): week = weeks[week_index] # Draw each day in a column. for day_index in range(len(week)): day = week[day_index] # Ignore days from other months. if day == 0: continue # Determine the position of this day in the image. x = (day_index + 1) * x_stride y = (week_index + 1) * y_stride # Mark the current day with a squircle. if day == time.day: squircle = Image.open(SQUIRCLE_FILE).convert(mode='RGBA') squircle_xy = (x - squircle.width // 2, y - squircle.height // 2) draw.bitmap(squircle_xy, squircle, HIGHLIGHT_COLOR) number_color = TODAY_COLOR event_color = TODAY_COLOR else: number_color = NUMBER_COLOR event_color = HIGHLIGHT_COLOR # Draw the day of the month number. number = str(day) draw_text(number, SUBVARIO_CONDENSED_MEDIUM, number_color, xy=(x, y - NUMBER_Y_OFFSET), image=image) # Draw a dot for each event. num_events = min(MAX_EVENTS, event_counts[day]) dot = Image.open(DOT_FILE).convert(mode='RGBA') if num_events > 0: events_width = (num_events * dot.width + (num_events - 1) * DOT_MARGIN) for event_index in range(num_events): event_offset = (event_index * (dot.width + DOT_MARGIN) - events_width // 2) dot_xy = [ x + event_offset, y + DOT_OFFSET - dot.width // 2 ] draw.bitmap(dot_xy, dot, event_color) return image
class YearCalendar(object): '''A year calendar with 12 pages for each month. All attributes have reasonable defaults. However, they can be overridden in constructor as well as directly. The most important method is "render" that renders the calendar into a specified file. Fonts: Any font can be used. Reportlab by default uses Adobe fonts. Module font_loader however tries to import as many system fonts (TTF) as possible (see there). You can register your own fonts as well. Scaling algorithms: These algorithms (as scaling attribute) determine how the pictures are scaled (and transformed) to fit in the desired area. - "squarecrop" : Take square area and put a cropped picture inside - "fit" : Take the largest area possible and fit the whole image inside Attributes: - holidays: A list of datetime.date's (default: from locale) - pagesize: (width, height) in points (default: A4) - scaling: Scaling algorithm (default: squarecrop, see above) - margins: (top, right, bottom, left) in points (default: 1.33cm) - title_font_name: Name of a registered font (see above) - title_font_size: Month title font size in pt (default 24) - title_font_variant: Month title font variant (see font_loader) ''' def __init__(self, year, pictures, locale=DefaultLocale(), special_days=[], **kwargs): """Constructor with all initialization. :param year: The year in YYYY format. :param pictures: A picture source (collection with indexes 1..12). :param scaling: Algorithm for scaling pictures (default squarecrop, see) :param kwargs: A dictionary of attributes to be overridden (see class description) """ self.year = year self.pictures = pictures self.locale = locale self.special_days = special_days self.scaling = kwargs.get("scaling", "squarecrop") self.holidays = kwargs.get("holidays", self.locale.holidays(self.year)) self.pagesize = kwargs.get("pagesize", A4) self.margins = kwargs.get("margins", (1.33*cm,) * 4) # top, right, bottom, left self.max_table_height = kwargs.get("max_table_height", self.content_height / 4) self.title_font_name = kwargs.get("title_font_name", "DejaVu Sans") self.title_font_variant = kwargs.get("title_font_variant", font_loader.BOLD) self.title_margin = kwargs.get("title_margin", 6 * mm) self.title_font_size = kwargs.get("title_font_size", 24) #pt self.cell_font_name = kwargs.get("cell_font_name", "DejaVu Sans") self.cell_font_variant = kwargs.get("cell_font_variant", font_loader.OBLIQUE) self.cell_font_size = kwargs.get("cell_font_size", 16) #pt self.cell_padding = kwargs.get("cell_padding", 6) self.cell_spacing = kwargs.get("cell_spacing", 2 * mm) self.week_color = kwargs.get("week_color", colors.Color(0.2, 0.2, 0.2)) self.week_bgcolor = kwargs.get("week_bgcolor", colors.white) self.weekend_color = kwargs.get("weekend_color", colors.white) self.weekend_bgcolor = kwargs.get("weekend_bgcolor", colors.Color(1.0, 0.5, 0.5)) self.holiday_color = kwargs.get("holiday_color", self.weekend_color) self.holiday_bgcolor = kwargs.get("holiday_bgcolor", colors.Color(1.0, 0.2, 0.2)) self.special_day_color = kwargs.get("special_day_color", colors.white) self.special_day_bgcolor = kwargs.get("special_day_bgcolor", colors.Color(0.2, 0.2, 1.0)) # Initialize calendar self._calendar = Calendar(self.locale.first_day_of_week) def _repr_html_(self): """HTML representation, useful for IPython notebook.""" from io import BytesIO from base64 import b64encode html = "<div>" html += "<div style='font-size:124%'>Calendar for year {0}</div>".format(self.year) html += "<div>" thumb_size = 64 for i, image in enumerate(self.pictures): pil_im = PIL.Image.open(image) pil_im = self._scale_picture(pil_im, 1)[0] pil_im.thumbnail((thumb_size, thumb_size)) b = BytesIO() pil_im.save(b, format='png') image_data = b64encode(b.getvalue()).decode('utf-8') html += "<img style='display:inline-block; margin:1px' alt='{0}' src='data:image/png;base64,{1}'/>".format(i, image_data) html += "</div>" html += "</div>" return html @property def width(self): return self.pagesize[0] @property def height(self): return self.pagesize[1] @property def content_width(self): '''Content width (= paper width - margins).''' return self.width - self.margins[1] - self.margins[3] @property def content_height(self): '''Content height (= paper height - margins).''' return self.height - self.margins[0] - self.margins[2] @property def cell_height(self): '''Height of a day cell in month calendar.''' return self.max_table_height / 6 @property def cell_width(self): '''Width of a day cell in month calendar.''' return self.content_width / 7 def set_font(self, name, size=12, variant="normal"): font = font_loader.get_font_name(name, variant) self.canvas.setFont(font, size) def _style_holidays_and_special_days(self, month, table_style): '''Set colours for all cells based on categories. Categories: weekend, holidays, special days. ''' calendar = self._calendar.monthdatescalendar(self.year, month) for row, days in enumerate(calendar): for column, day in enumerate(days): if day.month != month: continue if day.weekday() in self.locale.weekend: table_style.add("BACKGROUND", (column, row), (column, row), self.weekend_bgcolor) table_style.add("TEXTCOLOR", (column, row), (column, row), self.weekend_color) if day in self.holidays: table_style.add("BACKGROUND", (column, row), (column, row), self.holiday_bgcolor) table_style.add("TEXTCOLOR", (column, row), (column, row), self.holiday_color) if day in self.special_days: table_style.add("BACKGROUND", (column, row), (column, row), self.special_day_bgcolor) table_style.add("TEXTCOLOR", (column, row), (column, row), self.special_day_color) def _scale_picture(self, image, max_picture_height): '''Apply the scaling algorithm. :param image: PIL object :max_picture_height: the vertical area that can be occupied Return tuple (transformed PIL image object, PDF width, PDF height) ''' width, height = image.size if self.scaling == "squarecrop": crop_size = min(width, height) crop_coords = ( (width - crop_size) // 2, (height - crop_size) // 2, (width - crop_size) // 2 + crop_size, (height - crop_size) // 2 + crop_size ) cropped = image.crop(crop_coords) size = min(self.content_width, max_picture_height) return cropped, size, size elif self.scaling == "fit": max_width = self.content_width max_height = max_picture_height if width * max_height > height * max_width: height = max_width * height / width width = max_width else: width = max_height * width / height height = max_height return image, width, height else: raise Exception("Unknown scaling: %s" % self.scaling) def _render_picture(self, month, max_picture_height): '''Draw the picture. It is automatically scaled using the selected algorithm. ''' image = PIL.Image.open(self.pictures[month]) image, width, height = self._scale_picture(image, max_picture_height) left = (self.content_width - width) / 2 + self.margins[3] top = self.content_height + self.margins[0] - height self.canvas.drawImage(ImageReader(image), left, top, width=width, height=height) def _render_month(self, month): '''Render one page with a month.''' table_data = self._calendar.monthdayscalendar(self.year, month) table_data = [ [ day or None for day in week ] for week in table_data ] table = Table(table_data, colWidths=(self.cell_width,) * 7, rowHeights=(self.cell_height,) * len(table_data) ) style = TableStyle() for padding in ("TOP", "RIGHT", "BOTTOM", "LEFT"): style.add(padding + "PADDING", (0, 0), (-1, -1), self.cell_padding) for position in ("BEFORE", "AFTER", "ABOVE", "BELOW"): style.add("LINE" + position, (0, 0), (-1, -1), self.cell_spacing / 2, colors.white) font_name = font_loader.get_font_name(self.cell_font_name, self.cell_font_variant) style.add("FONT", (0, 0), (-1, -1), font_name, self.cell_font_size) style.add("ALIGN", (0, 0), (-1, -1), "RIGHT") style.add("VALIGN", (0, 0), (-1, -1), "MIDDLE") style.add("BACKGROUND", (0, 0), (-1, -1), self.week_bgcolor) style.add("TEXTCOLOR", (0, 0), (-1, -1), self.week_color) self._style_holidays_and_special_days(month, style) table.setStyle(style) table_width, table_height = table.wrapOn(self.canvas, 7*self.cell_width, 6*self.cell_height) table.drawOn(self.canvas, self.margins[3], self.margins[2]) # Render title title_position = (self.margins[3], self.margins[2] + table_height + self.title_margin) self.set_font(self.title_font_name, self.title_font_size, variant=self.title_font_variant) self.canvas.drawString(title_position[0], title_position[1], self.locale.month_title(self.year, month)) # Render picture self._render_picture(month, self.content_height - self.title_font_size - 2 * self.title_margin - table_height) self.canvas.showPage() def render_title_page(self): # TODO: Implement # self.canvas.showPage() pass def render(self, file_name): '''Render the calendar into a PDF file. :param file_name: Path to write to. ''' self.canvas = canvas.Canvas(file_name, self.pagesize) self.canvas.setTitle("{0} {1}".format(self.locale.calendar_name, self.year)) self.render_title_page() # TODO: To be implemented for month in range(1, 13): self._render_month(month) self.canvas.save()
def display_w_screen(self): """Main operating screen for the user""" # clear screen from previous widgets for w in self.winfo_children(): w.destroy() # frame placement and settings self.pack(fill=tk.BOTH, expand=1) self.configure(bg='SpringGreen3') month_dict = { 1: 'January', 2: 'February', 3: 'March', 4: 'April', 5: 'May', 6: 'June', 7: 'July', 8: 'August', 9: 'September', 10: 'October', 11: 'November', 12: 'December' } # labels for printing username, year and month label_username = tk.Label(self, text=f'{View.username}') label_y = tk.Label(self, text=f'{View.y}') label_m = tk.Label(self, text=f'{month_dict[View.m]}') label_username.grid(row=0, column=0, columnspan=7, sticky='w' + 'e') label_y.grid(row=1, column=2, columnspan=3, sticky='w' + 'e') label_m.grid(row=2, column=2, columnspan=3, sticky='w' + 'e') # buttons for scrolling months btn_l = tk.Button(self, text='<-', command=self.minus_month) btn_r = tk.Button(self, text='->', command=self.plus_month) btn_l.grid(row=1, rowspan=2, column=0, columnspan=2, sticky='n' + 's' + 'w' + 'e') btn_r.grid(row=1, rowspan=2, column=5, columnspan=2, sticky='n' + 's' + 'w' + 'e') # button for register changes btn_register_changes = tk.Button(self, text='Enter', height=2, width=10) btn_register_changes.place(x=140, y=380) btn_register_changes.bind('<1>', self.register_changes) d = Calendar() # determine and placement day's buttons for each months btn = [] for i in range(len(d.monthdayscalendar(View.y, View.m) * 7)): c, r = divmod(i, len(d.monthdayscalendar(View.y, View.m))) # text for button is a day btn_text = str(d.monthdayscalendar(View.y, View.m)[r][c]) # button's color according to existing date in [dates] color = View.colors[f'{View.y} {View.m} {btn_text}'] if \ f'{View.y} {View.m} {btn_text}' in View.colors else 'OliveDrab2' # form list of buttons btn.append( tk.Button(self, text=btn_text, height=3, width=6, bg=color)) # buttons, not in current month not place if str(d.monthdayscalendar(View.y, View.m)[r][c]) != '0': btn[i].grid(row=r + 3, column=c) btn[i].bind('<Button-1>', self.click)