def generate_month_calendar(self, year, month_seqnum): """This method is responsible for generating 6-weeks monthdatescalendar for the given month of the year""" # Sunday is specified to be the first day of the week (necessary for appropriate deployment of the days of month) cal = Calendar(firstweekday=6) # list of weeks of the given month of the year as full weeks; week is list of seven datetime.date objects month_dates_cal = cal.monthdatescalendar(year, month_seqnum) weeks_cnt = len( month_dates_cal ) # i.e. weeks in the monthdatescalendar generated by Python # adding either one or two weeks to complete to the total of 6 weeks if weeks_cnt < 6: # in case first day of the given month is the first day of the week(i.e. Sunday), # it is necessary to add the last week of the preceding month if month_dates_cal[0][0].day == 1: prev_month_seqnum = month_seqnum - 1 prev_year = year if prev_month_seqnum == 0: prev_month_seqnum = 12 prev_year = year - 1 month_dates_cal.insert( 0, cal.monthdatescalendar(prev_year, prev_month_seqnum)[-1] ) # week index is -1 i.e. the last week of the preceding month weeks_cnt = len(month_dates_cal) # if (either originally or after adding the last week of the preceding month) one week is missing to complete to the total of 6, # it is necessary to append the first week of the succeeding month if weeks_cnt == 5: next_year = year next_month_seqnum = month_seqnum + 1 if next_month_seqnum == 13: next_month_seqnum = 1 next_year = year + 1 nextmonth_cal = cal.monthdatescalendar(next_year, next_month_seqnum) nextmonth_week = 1 # first week of the succeeding month contains days of the given month therefore the second week is to be appended if nextmonth_cal[0][0].day == 1: nextmonth_week = 0 # in case the first day of the succeeding month is the first day of the week(i.e. Sunday), the first week is to be appended month_dates_cal.append(nextmonth_cal[nextmonth_week]) # list flattening: month_dates_cal = [day for week in month_dates_cal for day in week] return month_dates_cal
def _calendar(selected_date): year, month = selected_date.year, selected_date.month filters = {'date__year': year, 'date__month': month} bookings = {b.date: b for b in Booking.objects.filter(**filters)} calendar = Calendar(firstweekday=6) for week in calendar.monthdatescalendar(year, month): yield [(day, bookings.get(day)) for day in week]
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')
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
def my_request(login_id, month_year): if month_year and not isinstance(month_year, date): month_year = datetime.strptime(month_year, '%Y-%m').date() session = get_db_session() operator = OperatorQuery(session).get_operator_of_user_id(current_user.id) CalendarDay = namedtuple('CalendarDay', ('date', 'outer_month', 'notices', 'requests')) def is_between(date, start, end): return start.date() <= date <= end.date() def create_date(date, notices): return CalendarDay( date, date.year != month_year.year or date.month != month_year.month, notices, [ request for request in operator.requests if is_between(date, request.at_from, request.at_to) ]) calender = Calendar() calender.setfirstweekday(SUNDAY) weeks = [[create_date(_date, None) for _date in week] for week in calender.monthdatescalendar( month_year.year, month_year.month)] return render_template('request.html', month_year=month_year, weeks=weeks)
def jourl_avec_jour(annee, mois, jour): calendar = Calendar() months = calendar.monthdatescalendar(annee, mois) for week in months: for i in range(len(week)): if week[i].day == jour: return jours[i]
def render(self, context): mycal = Calendar() context[self.var_name] = mycal.monthdatescalendar( int(self.year.resolve(context)), int(self.month.resolve(context)) ) return ""
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)
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)
def cal_event(event_id, year, month): notifications = get_notifications(current_user.id) cal = Calendar(6) if year == 0 and month == 0: year = date.today().year month = date.today().month return redirect( url_for('cal_event', year=year, month=month, event_id=event_id)) weeks = cal.monthdatescalendar(year, month) coming_up = db.session.query(Event).join( UserEvent, UserEvent.event_id == Event.id).filter( UserEvent.user_id == current_user.id, UserEvent.accepted == 1).all() event = Event.query.get(event_id) user_event = UserEvent.query.filter_by(event_id=event_id, user_id=current_user.id).first() eventform = eventform = UpdateEventForm() friendform = AddFriendForm() today = datetime.date.today() return render_template("cal_event.html", notifications=notifications, user=current_user, year=year, mon=month, weeks=weeks, coming_up=coming_up, event=event, user_event=user_event, eventform=eventform, friendform=friendform, today=today)
def _calendar(selected_date, selected_place): place = selected_place year, month = selected_date.year, selected_date.month filters = {'date__year': year, 'date__month': month, 'place': place} bookings = {b.date: b for b in Booking.objects.filter(**filters)} calendar = Calendar(firstweekday=6) for week in calendar.monthdatescalendar(year, month): yield [(day, bookings.get(day)) for day in week]
def index(year): cal = Calendar(0) try: if not year: year = date.today().year cal_list = [cal.monthdatescalendar(year, i + 1) for i in xrange(12)] except Exception, e: abort(404)
def index(year): cal = Calendar(0) try: if not year: year = date.today().year cal_list = [cal.monthdatescalendar(year, i+1) for i in xrange(12)] except Exception, e: abort(404)
def to_calendar(interval, series): start, stop = get_calendar_range(interval, 3) legend, values = colorize( [ '#fae5cf', '#f9ddc2', '#f9d6b6', '#f9cfaa', '#f8c79e', '#f8bf92', '#f8b786', '#f9a66d', '#f99d60', '#fa9453', '#fb8034', '#fc7520', '#f9600c', '#f75500', ], [value for timestamp, value in series if value is not None], ) value_color_map = dict(values) value_color_map[None] = '#F2F2F2' series_value_map = dict(series) def get_data_for_date(date): dt = datetime(date.year, date.month, date.day, tzinfo=pytz.utc) ts = to_timestamp(dt) value = series_value_map.get(ts, None) return ( dt, { 'value': value, 'color': value_color_map[value], } ) calendar = Calendar(6) sheets = [] for year, month in map(index_to_month, range(start, stop + 1)): weeks = [] for week in calendar.monthdatescalendar(year, month): weeks.append(map(get_data_for_date, week)) sheets.append(( datetime(year, month, 1, tzinfo=pytz.utc), weeks, )) return { 'legend': list(legend.keys()), 'sheets': sheets, }
def list_sessions(request, year=None, month=None): args = {} today = date.today() if year is None: year = today.year month = today.month else: year = int(year) month = int(month) current = date(year, month, 1) nextmonth = current + relativedelta(months=1) prevmonth = current - relativedelta(months=1) args["year"] = year args["month"] = month args["current"] = current args["prevmonth"] = prevmonth args["nextmonth"] = nextmonth cal = Calendar() days = cal.monthdatescalendar(year, month) q = Q(nr_votes__gt=0) | Q(nr_statements__gt=0) date_q = Q(plsess__date__gte=current, plsess__date__lte=nextmonth) pl_items = PlenarySessionItem.objects.filter(q & date_q).select_related('plsess').order_by('plsess__date') acc = {} for pl_item in pl_items: statements, votes, plsess = acc.setdefault(pl_item.plsess.date, (0, 0, None)) statements += pl_item.nr_statements votes += pl_item.nr_votes plsess = pl_item.plsess.url_name acc[pl_item.plsess.date] = statements, votes, plsess def _date_to_info(d): info = {} info['date'] = d info['weekdayclass'] = "small" if d.weekday() in [5, 6] else "normal" info['today'] = d == today info['offmonth'] = d.month != current.month or d.year != current.year statements, votes, plsess = acc.setdefault(d, (0, 0, None)) info["statements"] = statements info["votes"] = votes info["plsess"] = plsess return info args["weeks"] = map(lambda w: map(_date_to_info, w), days) return render_to_response('new_sessions.html', args, context_instance=RequestContext(request))
def monthdates_cal(yr, m): ''' returns a month's list of weeks with the days as datetime.date objects :return: [datetime.date(2017-04-15), ....],[datetime.date(2017-04-22)...] ''' cal = Calendar(firstweekday=6) monthdates = cal.monthdatescalendar(yr, m) return monthdates
def index(year): conn = pymongo.MongoClient() db = conn.test cal = Calendar(0) try: if not year: year = date.today().year cal_list = [cal.monthdatescalendar(year, i + 1) for i in xrange(12)] except Exception, e: abort(404)
def index(year): conn = pymongo.MongoClient() db = conn.test cal = Calendar(0) try: if not year: year = date.today().year cal_list = [cal.monthdatescalendar(year, i+1) for i in xrange(12)] except Exception, e: abort(404)
def index(request): appointment_list = Appointment.objects.all() try: patient = Patient.objects.get(user=request.user) appointment_list = Appointment.objects.filter( patient=patient).order_by('-time')[:5] except: patient = None try: doctor = Doctor.objects.get(user=request.user) appointment_list = Appointment.objects.filter( doctor=doctor).order_by('-time')[:5] except: doctor = None today = date.today() calendar = Calendar(firstweekday=6) iter = calendar.monthdatescalendar(today.year, today.month) month = today.strftime("%B") checkyearlast = today.year checkyearnext = today.year lastmonth = today.month - 1 if lastmonth == 0: lastmonth = 12 checkyearlast = checkyearlast - 1 nextmonth = today.month + 1 if nextmonth == 13: nextmonth = 1 checkyearnext = checkyearnext + 1 context = { 'appointment_list': appointment_list, 'iter': iter, 'month': month, 'today': today, 'nextmonth': nextmonth, 'nextyear': checkyearnext, 'lastmonth': lastmonth, 'lastyear': checkyearlast, 'markdate': today } Stat.patientStats() if doctor is not None: return render(request, 'doctor_appointment_index.html', context) if patient is not None: return render(request, 'patient_appointment_index.html', context) return render(request, 'nurse_appointment_index.html', {'apps': appointment_list})
def current_week(cday): calendar = Calendar() months = calendar.monthdatescalendar(cday.year, cday.month) for week in months: for day in week: if day == cday: curr_week = week result = [] for i in range(len(curr_week)): result.append(Jour(curr_week[i])) return result
def index(year): cal = Calendar(0) try: if not year: year = date.today().year cal_list = [cal.monthdatescalendar(year, i + 1) for i in range(12)] except: abort(404) else: return render_template('cal.html', year=year, cal=cal_list) abort(404)
def week_calendar(days): cal = Calendar(6) today = date.today() + timedelta(days=days) weeks = cal.monthdatescalendar(today.year, today.month) current_week = [] for week in weeks: if week[0] <= today <= week[6]: current_week = week break return current_week
def __init__(self): self.begin_day = 1 self.year = 2016 self.month = 9 c = Calendar(firstweekday=self.begin_day) self.cal = c.monthdatescalendar(self.year, self.month) thursday = 4 - self.begin_day friday = 5 - self.begin_day sunday = 6 - self.begin_day monday = 1 - self.begin_day self.weekday_select = [thursday, friday]
def get_expiry_date(self, last_date, expiry): data_dow = self.dt_date.isoweekday() if 'week' in expiry.lower(): if last_date: return last_date + td(days=7) else: return self.dt_date + td(days=(6 - data_dow)) elif 'q' in expiry.lower(): quarter, year = expiry.split('-') month = int(quarter[1])*3 year = int(self.dt_date.strftime('%C') + year) c = Calendar() last_day = c.monthdatescalendar(year, month)[-1][-1] while not (last_day.month == month and last_day.isoweekday() <= 5): last_day = last_day - td(days=1) return last_day else: e_dt = datetime.strptime(expiry, '%b-%y') c = Calendar() fridays = [x[4] for x in c.monthdatescalendar(e_dt.year, e_dt.month)] if fridays[0].month == e_dt.month: return fridays[2] + td(days=1) else: return fridays[3] + td(days=1)
def trap_calendar(year): cal = Calendar(0) try: if year is None: year = date.today().year year_mod = year else: year_mod = year % 9999 if year_mod < 1: year_mod = 1 cal_list = [cal.monthdatescalendar(year_mod, i + 1) for i in xrange(12)] except Exception, e: logConsole(e)
def getweek(t): """ Given a specific datetime, it picks the corresponding week and returns an array containing the 7 dates corresponding to each day. """ # cal = Calendar(6) # sunday as first day of week cal = Calendar(1) # tuesday as first day weeks = [w for w in cal.monthdatescalendar(t.year, t.month)] for w in weeks: for d in w: if d.day == t.day: return w return []
def modify_worktime(): '''设置教师的常规工作时间''' new_worktime = request.form.get('new_worktime', '', type=str) username = request.form.get('username', '', type=str) teacher = User.query.filter_by(username=username, role_id=3, is_delete=False).first() if teacher: # 把工作时间字符串变成列表 new_worktime_list = new_worktime.split(';') # 上面是协管员视角的时间,还要转化为UTC时间,才能存储 # 让每个星期从星期天开始 cal = Calendar(6) # 随便获取一个完整的naive的星期的日期 week = cal.monthdatescalendar(2020, 2)[0] # 获取utc时区对象 utc = timezone('UTC') # 获取协管员时区对象 moderator_country = current_user.timezone if len(moderator_country) > 2: moderator_tz = country_timezones[moderator_country[:2]][int( moderator_country[-1])] else: moderator_tz = country_timezones[moderator_country][0] tz_obj = timezone(moderator_tz) # 用来存放按照这个星期来看,UTC的上课时间(年月日小时) temp = [] for w in new_worktime_list: date = week[int(w[0])] time = datetime(date.year, date.month, date.day, int(w[2:])) time = time.astimezone(tz_obj) time = time.astimezone(utc) temp.append(time) # datetime里的6代表星期天,也就是我定义的0,这里用一个字典来保存这种映射关系 weekday_map = {6: 0, 0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6} # 清空worktime_list列表,用于存储UTC的常规工作时间 new_worktime_list = [] for time in temp: # 依然要把每个工作时间点变成0-1的形式,存进列表 new_worktime_list.append( str(weekday_map[time.weekday()]) + '-' + str(time.hour)) new_worktime_list.sort() new_worktime = ';'.join(new_worktime_list) # 查询出worktime表中该老师对应的对象,把更新保存到数据库中 # 如果老师还没有这个对象,那就新建 work_time = teacher.work_time.first() or WorkTime() work_time.work_time = new_worktime work_time.teacher_id = teacher.id db.session.add(work_time) return jsonify({'msg': '已经成功设置了教师时间'}) return jsonify({'msg': '信息有误,请重试'})
def calendar(self): """generates calendars representing all meals in the session, as a list of Calendar.monthdatescalendar() lists. In those lists, the second values of tuples are the corresponding Meal objects. """ cur_month = None meals = self.meal_set.order_by('date') meals_dates = {} meals_count = 0 for meal in meals: cur_month = meal.date if cur_month is None else cur_month meals_count += 1 if meal.date not in meals_dates: if meal.date.date() not in meals_dates: meals_dates[meal.date.date()] = [] meals_dates[meal.date.date()].append(meal) if not cur_month: cur_month = datetime.now() months = [] cal = Calendar() month = cal.monthdatescalendar(cur_month.year, cur_month.month) remaining_meals = meals_count while remaining_meals > 0: month = cal.monthdatescalendar(cur_month.year, cur_month.month) for i, month_week in enumerate(month): for j, day in enumerate(month_week): meal_dates = meals_dates[day] if day in meals_dates and \ day.month == cur_month.month else [] remaining_meals -= len(meal_dates) month[i][j] = {'date': month[i][j], 'meals': meal_dates} months.append({'month': cur_month, 'dates': month}) cur_month = cur_month + relativedelta(months=1) return months
def index(year): cal = Calendar(0) try: if not year: year = date.today().year cal_list = [ cal.monthdatescalendar(year, i+1) for i in range(12) ] except: abort(404) else: return render_template('cal.html', year=year, cal=cal_list) abort(404)
def new(work_categories: [], month: int, year: int): calendar = SysCalendar() calendar.setfirstweekday(SUNDAY) monthdatescalendar = [ y for x in calendar.monthdatescalendar(year, month) for y in x if y.year == year and y.month == month ] days = [ DaySetting.new(x, day_abbr[x.weekday()], work_categories) for x in monthdatescalendar ] return MonthlySetting( UuidFactory.new_uuid(), month, year, days, len([x for x in monthdatescalendar if x.weekday() in [5, 6]]))
def current_week(): today = datetime.date.today() calendar = Calendar() months = calendar.monthdatescalendar(today.year, today.month) for week in months: for day in week: if day == today: curr_week = week result = [] for i in range(len(curr_week)): result.append( Jour(curr_week[i].year, curr_week[i].month, curr_week[i].day, jours[i])) return result
def index(): # check if user is logged in if session.get('username'): cal = Calendar(0) year = date.today().year month = date.today().month # cal_list = [cal.monthdatescalendar(year, i + 1) for i in xrange(12)] cal_list = [cal.monthdatescalendar(year, month)] return render_template('index.html', title = 'Dashboard', year = year, this_month = month, calendar = cal_list) else: return redirect(url_for('login'))
def trap_calendar(year): cal = Calendar(0) try: if year is None: year = date.today().year year_mod = year else: year_mod = year % 9999 if year_mod < 1: year_mod = 1 cal_list = [ cal.monthdatescalendar(year_mod, i + 1) for i in xrange(12) ] except Exception, e: logConsole(e)
def to_calendar(organization, interval, series): start, stop = get_calendar_range(interval, 3) legend, values = colorize( calendar_heat_colors, [value for timestamp, value in series if value is not None], ) value_color_map = dict(values) value_color_map[None] = "#F2F2F2" series_value_map = dict(series) # If global views are enabled we can generate a link to the day has_global_views = features.has("organizations:global-views", organization) def get_data_for_date(date): dt = datetime(date.year, date.month, date.day, tzinfo=pytz.utc) ts = to_timestamp(dt) value = series_value_map.get(ts, None) data = {"value": value, "color": value_color_map[value], "url": None} if has_global_views: url = reverse( "sentry-organization-issue-list", kwargs={"organization_slug": organization.slug} ) params = { "project": -1, "utc": True, "start": dt.isoformat(), "end": (dt + timedelta(days=1)).isoformat(), } url = f"{url}?{urlencode(params)}" data["url"] = absolute_uri(url) return (dt, data) calendar = Calendar(6) sheets = [] for year, month in map(index_to_month, range(start, stop + 1)): weeks = [] for week in calendar.monthdatescalendar(year, month): weeks.append(map(get_data_for_date, week)) sheets.append((datetime(year, month, 1, tzinfo=pytz.utc), weeks)) return {"legend": list(legend.keys()), "sheets": sheets}
class Meetup: def __init__(self, year, month): self.year = year self.month = month self.cal = Calendar() @property def monthly(self): return self.cal.monthdatescalendar(self.year, self.month) def weeks(self, ord_day): daily = ([ day for day in week if day.weekday() == ord_day and day.month == self.month ] for week in self.monthly) return [ordinal[0] for ordinal in filter(lambda d: d != [], daily)]
def to_calendar(interval, series): start, stop = get_calendar_range(interval, 3) legend, values = colorize( [ "#fae5cf", "#f9ddc2", "#f9d6b6", "#f9cfaa", "#f8c79e", "#f8bf92", "#f8b786", "#f9a66d", "#f99d60", "#fa9453", "#fb8034", "#fc7520", "#f9600c", "#f75500", ], [value for timestamp, value in series if value is not None], ) value_color_map = dict(values) value_color_map[None] = "#F2F2F2" series_value_map = dict(series) def get_data_for_date(date): dt = datetime(date.year, date.month, date.day, tzinfo=pytz.utc) ts = to_timestamp(dt) value = series_value_map.get(ts, None) return (dt, {"value": value, "color": value_color_map[value]}) calendar = Calendar(6) sheets = [] for year, month in map(index_to_month, range(start, stop + 1)): weeks = [] for week in calendar.monthdatescalendar(year, month): weeks.append(map(get_data_for_date, week)) sheets.append((datetime(year, month, 1, tzinfo=pytz.utc), weeks)) return {"legend": list(legend.keys()), "sheets": sheets}
def calendar(request, year=None, month=None, template="gnotty/calendar.html"): """ Show calendar months for the given year/month. """ try: year = int(year) except TypeError: year = datetime.now().year lookup = {"message_time__year": year} if month: lookup["message_time__month"] = month if hide_joins_and_leaves(request): lookup["join_or_leave"] = False messages = IRCMessage.objects.filter(**lookup) try: dates = messages.datetimes("message_time", "day") except AttributeError: dates = messages.dates("message_time", "day") days = [d.date() for d in dates] months = [] if days: min_date, max_date = days[0], days[-1] days = set(days) calendar = Calendar(SUNDAY) for m in range(1, 13) if not month else [int(month)]: lt_max = m <= max_date.month or year < max_date.year gt_min = m >= min_date.month or year > min_date.year if lt_max and gt_min: weeks = calendar.monthdatescalendar(year, m) for w, week in enumerate(weeks): for d, day in enumerate(week): weeks[w][d] = { "date": day, "in_month": day.month == m, "has_messages": day in days, } months.append({"month": date(year, m, 1), "weeks": weeks}) context = dict(settings) context["months"] = months return render(request, template, context)
def calendar(self): """ Renders the view as a list of months. """ if len(self.days) == 0: raise ValueError('Calendar rendering is not permitted without ' 'events.') cal = Calendar() months = [] remaining_days = sorted([k for k in self.days.keys()]) current_day = remaining_days[0].replace(day=1) remaining_events = len(self.events) while remaining_events > 0: month = cal.monthdatescalendar(current_day.year, current_day.month) month_view = [] for i, month_week in enumerate(month): month_view.append([]) for j, day in enumerate(month_week): if day.weekday() not in [5, 6]: # weekend removal month_view[i].append([]) if day in self.days: events, daily_events_count = \ self._extract_day_events(day) events = copy.deepcopy(events) events.add_attributes({ 'cur_month': day.month == current_day.month, }) remaining_events -= daily_events_count month_view[i][j] = events else: default_attributes = { 'active': False, 'today': day == date.today(), 'cur_month': day.month == current_day.month } month_view[i][j] = EventDay( day, attributes=default_attributes) months.append({'month': current_day, 'dates': month_view}) current_day = current_day + relativedelta(months=1) return months
def get_random_week_triplet(symbol): invalid_days = set([d for d in get_unavailable_dates(symbol)]) year = random.choice([2003,2004,2005,2006]) cal = Calendar() year_weeks = [] for month in range(12): weeks = cal.monthdatescalendar(year, month+1) for week in weeks: if week not in year_weeks: year_weeks.append(week) rwi = random.choice(range(len(year_weeks)-2)) prev_w, cur_w, next_w = year_weeks[rwi][:5], year_weeks[rwi+1][:5], year_weeks[rwi+2][:5] prev_w = [datetime(d.year, d.month, d.day) for d in prev_w] cur_w = [datetime(d.year, d.month, d.day) for d in cur_w] next_w = [datetime(d.year, d.month, d.day) for d in next_w] prev_w = [d for d in prev_w if d not in invalid_days] cur_w = [d for d in cur_w if d not in invalid_days] next_w = [d for d in next_w if d not in invalid_days] return prev_w, cur_w, next_w
def guide_cal_profile(year): cal = Calendar(0) try: if not year: year = date.today().year cal_list = [ cal.monthdatescalendar(year, i+1) for i in range(12) ] print(len(cal_list)) for i in cal_list: print(len(i)) print(cal_list[1][0]) except: abort(404) else: return render_template('guide/cal_profile.html', year=year, cal=cal_list) abort(404)
def calendar(request, year=None, month=None, template="gnotty/calendar.html", **kwargs): """ Show calendar months for the given year/month. """ try: year = int(year) except TypeError: year = datetime.now().year lookup = {"message_time__year": year} if month: lookup["message_time__month"] = month messages = IRCMessage.objects.filter(**lookup) days = [d.date() for d in messages.dates("message_time", "day")] min_date, max_date = days[0], days[-1] days = set(days) months = [] calendar = Calendar(SUNDAY) for m in range(1, 13) if not month else [int(month)]: lt_max = m <= max_date.month or year < max_date.year gt_min = m >= min_date.month or year > min_date.year if lt_max and gt_min: weeks = calendar.monthdatescalendar(year, m) for w, week in enumerate(weeks): for d, day in enumerate(week): weeks[w][d] = { "date": day, "in_month": day.month == m, "has_messages": day in days, } months.append({"month": date(year, m, 1), "weeks": weeks}) context = dict(settings) for key, value in kwargs: context['_'.join(['GNOTTY', key])] = value context["months"] = months return render(request, template, context)
def populate_calendar(): cal = Calendar(6) year = date.today().year month = date.today().month day = date.today().day dates = cal.monthdatescalendar(year, month) calendar_params = { 'api_key':session['api_key'], 'month':month, 'year':year } try: get_events = requests.get(CALENDAR_URL,params=calendar_params) events = get_events.json()['days'] return flask.render_template('dates.html', dates=dates, year=year, month=month, today=day, events=events, month_name=calendar.month_name[month]) except requests.exceptions.ConnectionError as e: return flask.render_template('dates.html', dates=dates, year=year, month=month, today=day) #return diff template??
def cal(year, month): notifications = get_notifications(current_user.id) cal = Calendar(6) if year == 0 and month == 0: year = date.today().year month = date.today().month return redirect(url_for('cal', year=year, month=month)) weeks = cal.monthdatescalendar(year, month) coming_up = db.session.query(Event).join( UserEvent, UserEvent.event_id == Event.id).filter( UserEvent.user_id == current_user.id, UserEvent.accepted == 1).all() eventform = NewEventForm() return render_template("cal.html", notifications=notifications, user=current_user, year=year, mon=month, weeks=weeks, coming_up=coming_up, eventform=eventform)
def _calendar(selected_date): year, month = selected_date.year, selected_date.month # Tapiri valid reservations (not cancelled nor expired) tp_filters = {'spot': 'TP', 'date__year': year, 'date__month': month} tp_reservations = { b.date: b for b in Reservation.valid_reservations.filter(**tp_filters) } # Salão de Festas valid reservations (not cancelled nor expired) sf_reservations = Reservation.objects.filter( spot='SF', date__year=year, date__month=month, ) sf_filters = {'spot': 'SF', 'date__year': year, 'date__month': month} sf_reservations = { b.date: b for b in Reservation.valid_reservations.filter(**sf_filters) } # Tapiri das Arvores valid reservations (not cancelled nor expired) ta_reservations = Reservation.objects.filter( spot='TA', date__year=year, date__month=month, ) ta_filters = {'spot': 'TA', 'date__year': year, 'date__month': month} ta_reservations = { b.date: b for b in Reservation.valid_reservations.filter(**ta_filters) } calendar = Calendar(firstweekday=6) today = date.today() for week in calendar.monthdatescalendar(year, month): yield [(day, tp_reservations.get(day), sf_reservations.get(day), ta_reservations.get(day)) for day in week]
def calendar(request, year=None, month=None, template="gnotty/calendar.html", **kwargs): """ Show calendar months for the given year/month. """ try: year = int(year) except TypeError: year = datetime.now().year lookup = {"message_time__year": year} if month: lookup["message_time__month"] = month messages = IRCMessage.objects.filter(**lookup) days = [d.date() for d in messages.dates("message_time", "day")] min_date, max_date = days[0], days[-1] days = set(days) months = [] calendar = Calendar(SUNDAY) for m in range(1, 13) if not month else [int(month)]: lt_max = m <= max_date.month or year < max_date.year gt_min = m >= min_date.month or year > min_date.year if lt_max and gt_min: weeks = calendar.monthdatescalendar(year, m) for w, week in enumerate(weeks): for d, day in enumerate(week): weeks[w][d] = { "date": day, "in_month": day.month == m, "has_messages": day in days, } months.append({"month": date(year, m, 1), "weeks": weeks}) context = dict(settings) for key, value in kwargs: context['_'.join(['GNOTTY',key])] = value context["months"] = months return render(request, template, context)
def calendar(request, year=None, month=None, template='chat/calendar.html'): """Show calender months for this given year/month.""" try: year = int(year) except TypeError: year = datetime.now().year lookup = {'time__year': year} if month: lookup['time__month'] = month if hide_joins_and_leaves(request): lookup['joins_or_leave'] = False messages = Message.objects.filter(**lookup) days = [d.date() for d in messages.dates('time', 'day')] months = [] if days: min_date, max_date = days[0], days[-1] days = set(days) calendar = Calendar(SUNDAY) for m in range(1, 13) if not month else [int(month)]: lt_max = m<= max_date.month or year < max_date.year gt_min = m >= min_date.month or year > min_date.year if lt_max and gt_min: weeks = calendar.monthdatescalendar(year, m) for w, week in enumerate(weeks): for d, day in enumerate(week): weeks[w][d] = { 'date': day, 'in_month': day.month == m, 'has_messages': day in days, } months.append({'month': date(year, m, 1), 'weeks': weeks}) context = dict(settings) context['months'] = months return render(request, template, context)
def calendar(request, year=None, month=None, template='chat/calendar.html'): """Show calender months for this given year/month.""" try: year = int(year) except TypeError: year = datetime.now().year lookup = {'time__year': year} if month: lookup['time__month'] = month if hide_joins_and_leaves(request): lookup['joins_or_leave'] = False messages = Message.objects.filter(**lookup) days = [d.date() for d in messages.dates('time', 'day')] months = [] if days: min_date, max_date = days[0], days[-1] days = set(days) calendar = Calendar(SUNDAY) for m in range(1, 13) if not month else [int(month)]: lt_max = m <= max_date.month or year < max_date.year gt_min = m >= min_date.month or year > min_date.year if lt_max and gt_min: weeks = calendar.monthdatescalendar(year, m) for w, week in enumerate(weeks): for d, day in enumerate(week): weeks[w][d] = { 'date': day, 'in_month': day.month == m, 'has_messages': day in days, } months.append({'month': date(year, m, 1), 'weeks': weeks}) context = dict(settings) context['months'] = months return render(request, template, context)
def _populate(self, year): # New Year's Day name = "New Year's Day" self[date(year, 1, 1)] = name # Birthday of Prophet, Mawlid in India # 12th day of 3rd Islamic month name = "Birth of Prophet" for offset in range(-1, 2, 1): islam_year = from_gregorian(year + offset, 11, 20)[0] y, m, d = to_gregorian(islam_year, 3, 12) if y == year: self[date(y, m, d)] = name # Chinese New Year name = "Chinese New Year" for offset in range(-1, 2, 1): ds = LunarDate(year + offset, 1, 1).toSolarDate() if ds.year == year: self[ds] = name # Tamil New Year # Note: it's not necessarily 04/14 # due to the local calendar # other possible dates are 04/13 and 04/15 name = "Tamil New Year" self[date(year, 4, 14)] = name # Good Friday name = "Good Friday" for offset in range(-1, 2, 1): ds = easter(year + offset) - rd(days=2) if ds.year == year: self[ds] = name # Labor Day name = "Labor Day" self[date(year, 5, 1)] = name # Buddha's Birthday name = "Wesak Day" for offset in range(-1, 2, 1): ds = LunarDate(year + offset, 4, 15).toSolarDate() if ds.year == year: self[ds] = name # King's birthday # https://www.thestar.com.my/news/nation/2017/04/26/ # Before 2017: first Saturday of June # 2017-2021: last Saturday of July name = "King's birthday" if year < 2017: c = Calendar(firstweekday=MONDAY) monthcal = c.monthdatescalendar(year, 6) l1 = len(monthcal) saturdays = [] for i in range(l1): if monthcal[i][5].month == 6: saturdays.append(monthcal[i][5]) self[saturdays[0]] = name elif (year >= 2017) and (year <= 2021): c = Calendar(firstweekday=MONDAY) monthcal = c.monthdatescalendar(year, 7) l1 = len(monthcal) saturdays = [] for i in range(l1): if monthcal[i][5].month == 7: saturdays.append(monthcal[i][5]) self[saturdays[-1]] = name # Eid al-Fitr name = "Eid al-Fitr" for offset in range(-1, 2, 1): islam_year = from_gregorian(year + offset, 6, 15)[0] y1, m1, d1 = to_gregorian(islam_year, 10, 1) y2, m2, d2 = to_gregorian(islam_year, 10, 2) if y1 == year: self[date(y1, m1, d1)] = name if y2 == year: self[date(y2, m2, d2)] = name # Malaysia Day name = "Malaysia Day" self[date(year, 9, 16)] = name # Feast of the Sacrifice name = "Feast of the Sacrifice" for offset in range(-1, 2, 1): islam_year = from_gregorian(year + offset, 8, 22)[0] y, m, d = to_gregorian(islam_year, 12, 10) if y == year: self[date(y, m, d)] = name # First Day of Muharram name = "First Day of Muharram" for offset in range(-1, 2, 1): islam_year = from_gregorian(year + offset, 9, 11)[0] y, m, d = to_gregorian(islam_year + 1, 1, 1) if y == year: self[date(y, m, d)] = name # Christmas name = "Christmas Day" self[date(year, 12, 25)] = name
def get_context_data(self, **kwargs): """ Injects variables necessary for rendering the calendar into the context. Variables added are: `calendar`, `weekdays`, `month`, `next_month` and `previous_month`. """ data = super(BaseCalendarMonthView, self).get_context_data(**kwargs) year = self.get_year() month = self.get_month() date = _date_from_string(year, self.get_year_format(), month, self.get_month_format()) cal = Calendar(self.get_first_of_week()) month_calendar = [] now = datetime.datetime.utcnow() date_lists = defaultdict(list) multidate_objs = [] for obj in data['object_list']: obj_date = self.get_start_date(obj) end_date_field = self.get_end_date_field() if end_date_field: end_date = self.get_end_date(obj) if end_date and end_date != obj_date: multidate_objs.append({ 'obj': obj, 'range': [x for x in daterange(obj_date, end_date)] }) continue # We don't put multi-day events in date_lists date_lists[obj_date].append(obj) for week in cal.monthdatescalendar(date.year, date.month): week_range = set(daterange(week[0], week[6])) week_events = [] for val in multidate_objs: intersect_length = len(week_range.intersection(val['range'])) if intersect_length: # Event happens during this week slot = 1 width = intersect_length # How many days is the event during this week? nowrap_previous = True # Does the event continue from the previous week? nowrap_next = True # Does the event continue to the next week? if val['range'][0] >= week[0]: slot = 1 + (val['range'][0] - week[0]).days else: nowrap_previous = False if val['range'][-1] > week[6]: nowrap_next = False week_events.append({ 'event': val['obj'], 'slot': slot, 'width': width, 'nowrap_previous': nowrap_previous, 'nowrap_next': nowrap_next, }) week_calendar = { 'events': week_events, 'date_list': [], } for day in week: week_calendar['date_list'].append({ 'day': day, 'events': date_lists[day], 'today': day == now.date(), 'is_current_month': day.month == date.month, }) month_calendar.append(week_calendar) data['calendar'] = month_calendar data['weekdays'] = [DAYS[x] for x in cal.iterweekdays()] data['month'] = date data['next_month'] = self.get_next_month(date) data['previous_month'] = self.get_previous_month(date) return data
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()
from calendar import Calendar from datetime import date cal = Calendar(0) month = cal.monthdatescalendar(2016, 6) for week in month: print week