def show_month(tm): (ly, lm, ld) = get_ludar_date(tm) print print u"%d年%d月%d日" % (tm.year, tm.month, tm.day), week_str(tm), print u"\t农历:", y_lunar(ly), m_lunar(lm), d_lunar(ld) print print u"日\t一\t二\t三\t四\t五\t六" c = Cal() ds = [d for d in c.itermonthdays(tm.year, tm.month)] count = 0 for d in ds: count += 1 if d == 0: print "\t", continue (ly, lm, ld) = get_ludar_date(datetime(tm.year, tm.month, d)) if count % 7 == 0: print d_str = str(d) if d == tm.day: d_str = u"*" + d_str print d_str + d_lunar(ld) + u"\t", print
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
def add_guideline(): """ Adds records with guidelines to db """ cal = Calendar() data = request.json year = int(data["year"]) month = int(data["month"]) workplace = Shop.query.filter_by(shopname=data["workplace"]).first() for day in cal.itermonthdays(year, month): if day > 0: guideline = Guidelines.query.filter_by(guide=workplace, year=year, month=month, day=day).first() if guideline: guideline.no_of_workers = data[str(day)] db.session.add(guideline) else: guideline = Guidelines(guide=workplace, year=year, month=month, day=day, no_of_workers=data[str(day)]) db.session.add(guideline) db.session.commit()
def add_user_to_sched(schedule, worker): """ adds new user to schedule :param schedule: selected schedule :param worker: worker to add """ worker = worker cal = Calendar() workplace = schedule.workplace schedule_workers = [] for ind_schedule in schedule.ind: if ind_schedule.worker not in schedule_workers: schedule_workers.append(ind_schedule.worker) workers = [] for employee in Shop.query.filter_by(shopname=workplace).first().works.all(): workers.append(str(employee)) if worker in workers and worker not in schedule_workers: for day in cal.itermonthdays(schedule.year, schedule.month): if day > 0: schedule_date = date(schedule.year, schedule.month, day) name = "%s-%s-%s" % (schedule_date, worker, schedule.workplace) pers_schedule = Personal_schedule(name=name, date=schedule_date, worker=worker, begin_hour=0, end_hour=0, hours_sum=0, event="off", workplace=workplace, includes_id=schedule.id) db.session.add(pers_schedule) db.session.commit() elif worker not in workers: flash("Taki pracownik nie jest przypisany do tego miejsa pracy") elif worker in schedule_workers: flash("Taki pracownik jest już w tym grafiku")
def show_month(tm): (ly, lm, ld) = get_ludar_date(tm) print( u"%d年%d月%d日" % (tm.year, tm.month, tm.day), week_str(tm), ) print(u"\t农历:", y_lunar(ly), m_lunar(lm), d_lunar(ld)) print(u"日\t一\t二\t三\t四\t五\t六") c = Cal() ds = [d for d in c.itermonthdays(tm.year, tm.month)] count = 0 for d in ds: print_str = '' if count == 0 and 0 in ds: print_str += '\t' count += 1 if d == 0: print(print_str + "\t", ) continue (ly, lm, ld) = get_ludar_date(datetime(tm.year, tm.month, d)) if count % 7 == 0: print(' ') d_str = str(d) if d == tm.day: d_str = u"*" + d_str print(d_str + d_lunar(ld) + u"\t", ) print(' ')
def show_month(tm): (ly, lm, ld) = get_lunar_date(tm) print print u"%d年%d月%d日" % (tm.year, tm.month, tm.day), week_str(tm), print u"\t农历:", y_lunar(ly), m_lunar(lm), d_lunar(ld) print print u"日\t一\t二\t三\t四\t五\t六" c = Cal() ds = [d for d in c.itermonthdays(tm.year, tm.month)] count = 0 for d in ds: count += 1 if d == 0: print "\t", continue (ly, lm, ld) = get_lunar_date(datetime(tm.year, tm.month, d)) if count % 7 == 0: print d_str = str(d) if d == tm.day: d_str = u"*" + d_str print d_str + d_lunar(ld) + u"\t", print
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
def get_journal_timetable_dictionary(month,day,user): _weekday = 0 _year = date.today().year record_db = Record.objects.filter(date=date(_year,month,day),user=user) cal = Calendar(_weekday) dayslist = [day for day in cal.itermonthdays(_year,month)] return {'year':_year,'month':month,'day':day,'daysinmonth':make_month(dayslist),'record_db':record_db}
def get_month_days(): today = get_local_today_min() cal = Calendar() month = filter( lambda d: d > 0, list(cal.itermonthdays(today.year, today.month)) ) return len(list(month))
def meetup_day(year, month, daystr, pos): cal = Calendar() # list of days by wanted weekday days = [day for day in cal.itermonthdays(year, month) if day > 0 and day_name[weekday(year, month, day)] == daystr] if pos == 'last': return date(year, month, days[-1]) elif pos[0].isdigit(): return date(year, month, days[int(pos[0])-1]) elif pos == 'teenth': return date(year, month, [day for day in days if 12 < day < 20][0]) else: return False
def getdayslist(): # 日時の準備(とりあえず先月で) import datetime from dateutil.relativedelta import relativedelta from calendar import Calendar prev = datetime.date.today() - relativedelta(months=1) cal = Calendar(firstweekday=6) dayslist = [] for d in cal.itermonthdays(prev.year, prev.month): if d != 0: dayslist.append("%d%d%02d" % (prev.year, prev.month, d)) return dayslist
def check_month_dir(path: str): """Check the MSG data from this month path.""" year, month = path[-7:-3], path[-2:] # .../2018/12 c = Calendar() for day in c.itermonthdays(int(year), int(month)): if day == 0: continue day_str = str(day).zfill(2) day_path_to_check = os.path.join(path, day_str) if not os.path.isdir(day_path_to_check): logging.warning(f"Could not find {day_path_to_check}") continue if check_day_dir(day_path_to_check): logging.info(f'{day_path_to_check} complete')
def format_month(self, the_month, timesheetdays, workingdays): month = '<tr><td><span class="date"><a href="/month/?month={}-{}">{}</a></span></td>'.format( self.year, the_month, the_month) c = Calendar() count_days_31 = 0 for d in c.itermonthdays(self.year, the_month): if d == 0: pass else: count_days_31 += 1 month += self.format_day(d, timesheetdays, workingdays) for i in range(31 - count_days_31): month += f'<td><span class="date"></span></td>' return f'{month}</tr>'
def get_empty_year(leap=False): """Creates a list representing a year, elements represent days. Elements are lists formatted as [day, month, weekday], where weekdays are all set to be 0. """ c = Calendar() l = list() if leap: year = 2020 else: year = 2019 for month in range(1, 13): for day in c.itermonthdays(year, month): if day != 0: l.append([day, month, 0]) return l
def getPrimeDays(year): p = PrimesGenerator() primes = [] cal = Calendar() multiple = int("1" + "0"*(len(str(year)))) for month in range(1, 12): for day in cal.itermonthdays(year, month): # itermonthdays tacks on (to the month front/back) days necessary to get a full week, all represented as 0's if day is 0: continue num = month*100*multiple + day*multiple + year if p.checkPrime(num): primes.append("%(month)s/%(day)s/%(year)s" % {"month": month, "day": day, "year": year}) return primes
def getDays_with_lunar(year, month, day): """根据年月日获得农历日期,与其月日一致的日期的公历""" (lyear, lmonth, lday) = get_ludar_date(datetime(year, month, day)) #print(str(year) + '-' + str(month) + '-' + str(day) + ':' + y_lunar(lyear) + m_lunar(lmonth) + d_lunar(lday)) days = [] y = 2012 c = Cal() while True: if y >= END_YEAR: break for m in xrange(1, 13): ds = [d for d in c.itermonthdays(y, m)] for d in ds: if d == 0: continue (ly, lm, ld) = get_ludar_date(datetime(y, m, d)) if (lmonth == lm) and (lday == ld): print(str(y) + '-' + str(m) + '-' + str(d) + ':' + y_lunar(ly) + m_lunar(lm) + d_lunar(ld)) days.append((y, m, d)) y += 1 return days
def fnGlob(fn, langs=[], year=util.gmtnow().year): """ transforms parameters to remote url filename scheme w/ parameters """ remote = [] # replace lang w/ available langs i = fn.find('$lang') dot = fn.rfind('.') if i>=0: (bef, sep, aft) = fn.partition('$lang') for lang in langs: remote.append(''.join([bef, '?lang=', lang, aft])) # replace $date with dates in year i = fn.find('$date') if i>=0: cal = Calendar() today = util.gmtnow() for i in range(0, len(remote)): # extract part of string before $date rbef = remote.pop(0).split('$date')[0] for month in range(1, 13): for day in cal.itermonthdays(year, month): if (0 == day): continue # don't know why, but day is 0 sometimes # we are not interested in older events if (year < today.year): continue if (year == today.year and month < today.month): continue # if (year == today.year and month == today.month \ # and day < today.day): continue remote.append('%s&year=%i&month=%i&day=%i' % \ (rbef, year, month, day)) # when no expansion happened at all, simply add the original string if 1 > len(remote): remote.append(fn) return remote
def compare_inds(schedule_id, last_accepted_id, unaccepted_ind, year, month): """ Compares individual schedules from unaccepted schedule with those from last accepted version of the schedule. :param schedule_id: id of unaccepted schedule :param last_accepted_id: id of he last accepted schedule :param unaccepted_ind: list of unaccepted schedule's individual schedules :param year: year of schedule :param month: month of schedule :return: list of differences """ changes = {} workers = find_workers(unaccepted_ind) cal = Calendar() for worker in workers: msg = [] for day in cal.itermonthdays(year, month): if day > 0: unaccepted_ind = Personal_schedule.query.filter_by(date=datetime(year, month, day), worker=worker, includes_id=schedule_id).first() last_accepted_ind = Personal_schedule.query.filter_by(date=datetime(year, month, day), worker=worker, includes_id=last_accepted_id).first() if unaccepted_ind and last_accepted_ind: if unaccepted_ind.begin_hour != last_accepted_ind.begin_hour or \ unaccepted_ind.end_hour != last_accepted_ind.end_hour or \ unaccepted_ind.event != last_accepted_ind.event: basic = { "year": year, "month": month, "day": day, "l_a_begin": last_accepted_ind.begin_hour, "l_a_end": last_accepted_ind.end_hour, "un_begin": unaccepted_ind.begin_hour, "un_end": unaccepted_ind.end_hour } msg.append(create_change_messages(unaccepted_ind, last_accepted_ind, basic)) changes[worker] = msg return changes
def post(request, pk=None, page_number=None): post_list = MinaPost.objects.order_by("created_date") paginator = Paginator(post_list, 1, adjacent_pages=3) try: if page_number: posts = paginator.page(page_number) post = posts.object_list[0] return redirect("mina:post", pk=post.pk) else: post = MinaPost.objects.get(pk=pk) except MinaPost.DoesNotExist: post = post_list.last() if post: return redirect("mina:post", pk=post.pk) return render(request, "mina/post.html") page_index = MinaPost.objects.get_index( post, compare_field="created_date", sort="ascending") + 1 posts = paginator.page(page_index) now = timezone.make_aware(datetime.now()) try: year = int(request.POST.get("year")) month = int(request.POST.get("month")) cal_date = timezone.make_aware(datetime(year, month, 1)) except: year = post.created_date.year month = post.created_date.month cal_date = post.created_date cal = Calendar() month_days = cal.itermonthdays(year, month) week_list = [[]] week = 0 for day in month_days: day_posts = [] if day: day_posts = MinaPost.objects.filter( created_date__year=year, created_date__month=month, created_date__day=day, ) dp_id_list = [post.id for post in day_posts] posts_id_list = [post.id for post in posts] day_info = { "day": day, "posts": day_posts, "today": True if now.year == year and now.month == month and now.day == day else False, "current": True if dp_id_list == posts_id_list else False, } week_list[week].append(day_info) if len(week_list[week]) == 7: week_list.append([]) week += 1 context = { "posts": posts, "week_list": week_list, "year": year, "month": month, "cal_prev_date": add_months(cal_date, -1), "cal_next_date": add_months(cal_date, +1), } return render(request, "mina/post.html", context)
def make_calendar(year, month, firstweekday="Mon"): firstweekday = list(day_abbrs).index(firstweekday) calendar = Calendar(firstweekday=firstweekday) month_days = [ None if not day else str(day) for day in calendar.itermonthdays(year, month) ] month_weeks = len(month_days)//7 workday = "linen" weekend = "lightsteelblue" def weekday(date): return (date.weekday() - firstweekday) % 7 def pick_weekdays(days): return [ days[i % 7] for i in range(firstweekday, firstweekday+7) ] day_names = pick_weekdays(day_abbrs) week_days = pick_weekdays([workday]*5 + [weekend]*2) source = ColumnDataSource(data=dict( days = list(day_names)*month_weeks, weeks = sum([ [str(week)]*7 for week in range(month_weeks) ], []), month_days = month_days, day_backgrounds = sum([week_days]*month_weeks, []), )) holidays = [ (date, summary.replace("(US-OPM)", "").strip()) for (date, summary) in us_holidays if date.year == year and date.month == month and "(US-OPM)" in summary ] holidays_source = ColumnDataSource(data=dict( holidays_days = [ day_names[weekday(date)] for date, _ in holidays ], holidays_weeks = [ str((weekday(date.replace(day=1)) + date.day) // 7) for date, _ in holidays ], month_holidays = [ summary for _, summary in holidays ], )) xdr = FactorRange(factors=list(day_names)) ydr = FactorRange(factors=list(reversed([ str(week) for week in range(month_weeks) ]))) x_scale, y_scale = CategoricalScale(), CategoricalScale() plot = Plot(x_range=xdr, y_range=ydr, x_scale=x_scale, y_scale=y_scale, plot_width=300, plot_height=300, outline_line_color=None) plot.title.text = month_names[month] plot.title.text_font_size = "16px" plot.title.text_color = "darkolivegreen" plot.title.offset = 25 plot.min_border_left = 0 plot.min_border_bottom = 5 rect = Rect(x="days", y="weeks", width=0.9, height=0.9, fill_color="day_backgrounds", line_color="silver") plot.add_glyph(source, rect) rect = Rect(x="holidays_days", y="holidays_weeks", width=0.9, height=0.9, fill_color="pink", line_color="indianred") rect_renderer = plot.add_glyph(holidays_source, rect) text = Text(x="days", y="weeks", text="month_days", text_align="center", text_baseline="middle") plot.add_glyph(source, text) xaxis = CategoricalAxis() xaxis.major_label_text_font_size = "11px" xaxis.major_label_standoff = 0 xaxis.major_tick_line_color = None xaxis.axis_line_color = None plot.add_layout(xaxis, 'above') hover_tool = HoverTool(renderers=[rect_renderer], tooltips=[("Holiday", "@month_holidays")]) plot.tools.append(hover_tool) return plot
def show_schedule_helper(schd, version): """ Creates dictionary with data for chosen schedule :param schd: name of schedule :param version: version of schedule :return: dict with schedule data """ cal = Calendar() schedule = Schedule.query.filter_by(name=schd, version=version, accepted=True).first() schd_id = schedule.id year = schedule.year month = schedule.month workplace = schedule.workplace hours = schedule.hrs_to_work version = schedule.version schd_dict = { "year": year, "month": month, "workplace": workplace, "hours": hours, "version": version } workers = [] for ind_sched in schedule.ind: if str(ind_sched.worker) not in workers: workers.append(str(ind_sched.worker)) schd_dict["workers"] = workers workers_hours = {} for worker in workers: worker_hours = 0 for ind_sched in schedule.ind: if ind_sched.worker == str(worker).replace("_", " "): worker_hours += ind_sched.hours_sum workers_hours[worker] = worker_hours for day in cal.itermonthdays(year, month): if day > 0: begin = Personal_schedule.query.filter_by( date=datetime(year, month, day), includes_id=schd_id, worker=worker.replace("_", " ")).first().begin_hour end = Personal_schedule.query.filter_by( date=datetime(year, month, day), includes_id=schd_id, worker=worker.replace("_", " ")).first().end_hour event = Personal_schedule.query.filter_by( date=datetime(year, month, day), includes_id=schd_id, worker=worker.replace("_", " ")).first().event h_sum = Personal_schedule.query.filter_by( date=datetime(year, month, day), includes_id=schd_id, worker=worker.replace("_", " ")).first().hours_sum billing_week = Personal_schedule.query.filter_by( date=datetime(year, month, day), includes_id=schd_id, worker=worker.replace("_", " ")).first().billing_week schd_dict["begin-%s-%d-%02d-%02d" % (worker, year, month, day)] = begin schd_dict["end-%s-%d-%02d-%02d" % (worker, year, month, day)] = end schd_dict["event-%s-%d-%02d-%02d" % (worker, year, month, day)] = event schd_dict["sum-%s-%d-%02d-%02d" % (worker, year, month, day)] = h_sum schd_dict["billing-week-%s-%d-%02d-%02d" % (worker, year, month, day)] = billing_week schd_dict["workers_hours"] = workers_hours return schd_dict
def create_sched(): """ Renders template with schedule :return: template with schedule """ path = request.args.get("path") filename = request.args.get("filename") file_path = path + filename year = int(request.args.get("year")) month = int(request.args.get("month")) workplace = request.args.get("workplace") hours = request.args.get("hours") db_workplace = Shop.query.filter_by(shopname=workplace).first() month_name = MONTH_NAMES[month - 1] cal = Calendar() prev = prev_schedule.prev_schedule(month, year, workplace) wb = load_workbook(file_path, data_only=True) # finding sheet sheets = wb.sheetnames sh = None for sheet in sheets: sheet_month = sheet.lower().replace("grafik_", "").lower() if sheet_month.capitalize() == month_name: sh = wb[sheet] if sh is None: flash("W pliku nie znaleziono grafiku na wybrany miesiąc.") return redirect( url_for("xlsx.upload_file", month=month, year=year, workplace=workplace)) # finding month cell month_cell = None for row in range(int(sh.max_row)): for col in range(int(sh.max_column)): current_cell = sh.cell(row=row + 1, column=col + 1) if isinstance(current_cell.value, str) and current_cell.value.lower().replace( " ", "") == month_name.lower(): month_cell = current_cell if month_cell is None: return wrong_file("miesiąca", month, year, workplace) # finding year year_cell = None for row in range(int(sh.max_row)): for col in range(int(sh.max_column)): current_cell = sh.cell(row=row + 1, column=col + 1) if isinstance(current_cell.value, int) and current_cell.value == year: year_cell = current_cell if year_cell is None: return wrong_file("roku", month, year, workplace) # finding workplace workplace_cell = None for row in range(int(sh.max_row)): for col in range(int(sh.max_column)): current_cell = sh.cell(row=row + 1, column=col + 1) if isinstance( current_cell.value, str) and current_cell.value.lower() == workplace.lower(): workplace_cell = current_cell if workplace_cell is None: return wrong_file("sklepu", month, year, workplace) # finding workers workers = {} wrong_workers = [] db_workers = [] worker_row = workplace_cell.row worker_col = cifs(workplace_cell.column) + 2 name_cell = sh.cell(row=worker_row, column=worker_col) surename_cell = sh.cell(row=worker_row + 1, column=worker_col) while name_cell.value is not None and surename_cell.value is not None: name = name_cell.value.replace( " ", "") + " " + surename_cell.value.replace(" ", "") workers[name] = surename_cell # workers.append(name) worker_col += 4 name_cell = sh.cell(row=worker_row, column=worker_col) surename_cell = sh.cell(row=worker_row + 1, column=worker_col) for worker in db_workplace.works.all(): db_workers.append(str(worker)) workers_to_schd = [] for worker in workers: workers_to_schd.append(str(worker.replace(" ", "_"))) for worker in workers_to_schd: if worker.replace("_", " ") not in db_workers: wrong_workers.append(worker.replace("_", " ")) if wrong_workers: flash("Sprawdź plik. Pracownicy nieprzypisani do sklepu: %s" % wrong_workers) return redirect( url_for("xlsx.upload_file", month=month, year=year, workplace=workplace)) # building dictionary with data for each day for each worker shdict = {} events = ("off", "in_work", "UW", "UNŻ", "L4", "UO", "UOJ", "UR", "UB") for worker in workers: for day in cal.itermonthdays(year, month): if day > 0: # begin hour begin = sh.cell(row=workers[worker].row + 1 + day, column=cifs(workers[worker].column)).value if begin is None: begin = "" shdict["begin-%s-%d-%02d-%02d" % (worker.replace(" ", "_"), year, month, day)] = begin # end hour end = sh.cell(row=workers[worker].row + 1 + day, column=cifs(workers[worker].column) + 1).value if end is None: end = "" shdict["end-%s-%d-%02d-%02d" % (worker.replace(" ", "_"), year, month, day)] = end # event event = sh.cell(row=workers[worker].row + 1 + day, column=cifs(workers[worker].column) + 3).value if event is None: event = "in_work" elif event == "X": event = "off" if event not in events: flash( "Niewłaściwe oznaczenie zdarzenia w dniu %02d-%02d-%04d u pracownika %s." % (day, month, year, worker)) return redirect( url_for("xlsx.upload_file", month=month, year=year, workplace=workplace)) shdict["event-%s-%d-%02d-%02d" % (worker.replace(" ", "_"), year, month, day)] = event flash("Wczytałem grafik na %s %s" % (month_name.lower(), year)) return render_template("xlsx/empty_schedule.html", title="grafiki", workplace=workplace, year=year, month=month, workers=workers_to_schd, month_name=month_name, wdn=WEEKDAY_NAMES, cal=cal, Billing_period=Billing_period, shdict=shdict, hours=hours, prev_shdict=prev["prev_shdict"], prev_month=prev["month"], prev_hours=prev["hours"], prev_month_name=prev["month_name"], prev_year=prev["year"], prev_workers=prev["workers"], workers_hours=prev["workers_hours"])
def prev_schedule(month, year, workplace): """ :param month: month of schedule :param year: year of schedule :param workplace: workplace for which schedule has to be create :return: dictionary with all needed data """ cal = Calendar() if month == 1: prev_month = 12 prev_year = year - 1 else: prev_month = month - 1 prev_year = year prev_month_name = MONTH_NAMES[prev_month - 1] try: prev_month_last_version = Schedule.query.filter_by(year=prev_year, month=prev_month, workplace=workplace, accepted=True).order_by(Schedule.version.desc()).first().\ version prev_month_shd = Schedule.query.filter_by( year=prev_year, month=prev_month, workplace=workplace, version=prev_month_last_version).first() except AttributeError: prev_month_shd = None if prev_month_shd is not None: prev_schd_id = prev_month_shd.id prev_workers = [] for pers_schedule in prev_month_shd.ind: if str(pers_schedule.worker).replace(" ", "_") not in prev_workers: prev_workers.append( str(pers_schedule.worker).replace(" ", "_")) prev_hours = prev_month_shd.hrs_to_work prev_shdict = {} workers_hours = {} for worker in prev_workers: worker_hours = 0 for p_schedule in prev_month_shd.ind: if p_schedule.worker == str(worker).replace("_", " "): worker_hours += p_schedule.hours_sum workers_hours[worker] = worker_hours for worker in prev_workers: for day in cal.itermonthdays(prev_year, prev_month): if day > 0: begin = Personal_schedule.query.filter_by( date=datetime(prev_year, prev_month, day), includes_id=prev_schd_id, worker=worker.replace("_", " ")).first().begin_hour end = Personal_schedule.query.filter_by( date=datetime(prev_year, prev_month, day), includes_id=prev_schd_id, worker=worker.replace("_", " ")).first().end_hour event = Personal_schedule.query.filter_by( date=datetime(prev_year, prev_month, day), includes_id=prev_schd_id, worker=worker.replace("_", " ")).first().event h_sum = Personal_schedule.query.filter_by( date=datetime(prev_year, prev_month, day), includes_id=prev_schd_id, worker=worker.replace("_", " ")).first().hours_sum billing_week = Personal_schedule.query.filter_by( date=datetime(prev_year, prev_month, day), includes_id=prev_schd_id, worker=worker.replace("_", " ")).first().billing_week prev_shdict["begin-%s-%d-%02d-%02d" % (worker, prev_year, prev_month, day)] = begin prev_shdict["end-%s-%d-%02d-%02d" % (worker, prev_year, prev_month, day)] = end prev_shdict["event-%s-%d-%02d-%02d" % (worker, prev_year, prev_month, day)] = event prev_shdict["sum-%s-%d-%02d-%02d" % (worker, prev_year, prev_month, day)] = h_sum prev_shdict["billing-week-%s-%d-%02d-%02d" % (worker, prev_year, prev_month, day)] = billing_week else: prev_shdict = None prev_hours = None prev_workers = None workers_hours = None prev = { "prev_shdict": prev_shdict, "hours": prev_hours, "workers": prev_workers, "workers_hours": workers_hours, "year": prev_year, "month": prev_month, "month_name": prev_month_name } return prev
def make_calendar(year, month, firstweekday="Mon"): firstweekday = list(day_abbrs).index(firstweekday) calendar = Calendar(firstweekday=firstweekday) month_days = [ None if not day else str(day) for day in calendar.itermonthdays(year, month) ] month_weeks = len(month_days)//7 workday = "linen" weekend = "lightsteelblue" def weekday(date): return (date.weekday() - firstweekday) % 7 def pick_weekdays(days): return [ days[i % 7] for i in range(firstweekday, firstweekday+7) ] day_names = pick_weekdays(day_abbrs) week_days = pick_weekdays([workday]*5 + [weekend]*2) source = ColumnDataSource(data=dict( days = list(day_names)*month_weeks, weeks = sum([ [str(week)]*7 for week in range(month_weeks) ], []), month_days = month_days, day_backgrounds = sum([week_days]*month_weeks, []), )) holidays = [ (date, summary.replace("(US-OPM)", "").strip()) for (date, summary) in us_holidays if date.year == year and date.month == month and "(US-OPM)" in summary ] holidays_source = ColumnDataSource(data=dict( holidays_days = [ day_names[weekday(date)] for date, _ in holidays ], holidays_weeks = [ str((weekday(date.replace(day=1)) + date.day) // 7) for date, _ in holidays ], month_holidays = [ summary for _, summary in holidays ], )) xdr = FactorRange(factors=list(day_names)) ydr = FactorRange(factors=list(reversed([ str(week) for week in range(month_weeks) ]))) x_scale, y_scale = CategoricalScale(), CategoricalScale() plot = Plot(x_range=xdr, y_range=ydr, x_scale=x_scale, y_scale=y_scale, plot_width=300, plot_height=300, outline_line_color=None) plot.title.text = month_names[month] plot.title.text_font_size = "12pt" plot.title.text_color = "darkolivegreen" plot.title.offset = 25 plot.min_border_left = 0 plot.min_border_bottom = 5 rect = Rect(x="days", y="weeks", width=0.9, height=0.9, fill_color="day_backgrounds", line_color="silver") plot.add_glyph(source, rect) rect = Rect(x="holidays_days", y="holidays_weeks", width=0.9, height=0.9, fill_color="pink", line_color="indianred") rect_renderer = plot.add_glyph(holidays_source, rect) text = Text(x="days", y="weeks", text="month_days", text_align="center", text_baseline="middle") plot.add_glyph(source, text) xaxis = CategoricalAxis() xaxis.major_label_text_font_size = "8pt" xaxis.major_label_standoff = 0 xaxis.major_tick_line_color = None xaxis.axis_line_color = None plot.add_layout(xaxis, 'above') hover_tool = HoverTool(renderers=[rect_renderer], tooltips=[("Holiday", "@month_holidays")]) plot.tools.append(hover_tool) return plot
import calendar from calendar import Calendar # 返回一周内各天的名称 c1 = Calendar() #不指定参数的话默认星期一(0 is Monday) print("返回一周内各天的名称: ", list(c1.iterweekdays())) c2 = Calendar(firstweekday=calendar.SATURDAY) #指定今天是星期六 print("返回指定周几后一周内各天的名称: ", list(c2.iterweekdays())) # 返回指定年,月的所有天数,会自动加上月前与月后的天数来令到每周都不会缺少日期(比如10.31是周三,会补上11.1,11.2与11.3来补全这一周) # 返回的迭代器是以datetime.date为元素 print("返回指定年,月的所有天数(datetime.date): ", list(c2.itermonthdates(2018, 10))) # 返回指定年,月的所有天数,不会自动加上月前与月后的天数来令到每周都不会缺少日期,缺少的天数为设为0 # 返回的迭代器是以int为元素 print("返回指定年,月的所有天数(int): ", list(c2.itermonthdays(2018, 10))) # 返回指定年,月的所有天数,不会自动加上月前与月后的天数来令到每周都不会缺少日期,缺少的天数为设为0 # 返回的迭代器是以元组为元素, 元组里是(几号,星期x)这样 print("返回指定年,月的所有天数(tuple): ", list(c2.itermonthdays2(2018, 10))) # 以周为单位返回指定年,月的所有天数,会自动加上月前与月后的天数来令到每周都不会缺少日期(比如10.31是周三,会补上11.1,11.2与11.3来补全这一周) # 返回的列表是每七个datetime.date列表为元素 print("返回指定年,月的所有天数(tuple): ", c2.monthdatescalendar(2018, 10))
def make_calendar(sp500_data_lst, djia_data_lst, nasdaq_data_lst, twitter_data_lst, holiday_lst, nyt_data_lst, approval_data_lst, generic_dem_lst, generic_rep_lst, plot_wid, plot_ht, year, month, firstweekday="Sun"): firstweekday = list(day_abbrs).index(firstweekday) calendar = Calendar(firstweekday=firstweekday) month_days = [ None if not day else str(day) for day in calendar.itermonthdays(year, month) ] month_weeks = len(month_days) // 7 workday = "linen" weekend = "lightsteelblue" def weekday(date): return (date.weekday() - firstweekday) % 7 def pick_weekdays(days): return [days[i % 7] for i in range(firstweekday, firstweekday + 7)] day_names = pick_weekdays(day_abbrs) week_days = pick_weekdays([workday] * 5 + [weekend] * 2) source = ColumnDataSource(data=dict( days=list(day_names) * month_weeks, weeks=sum([[str(week)] * 7 for week in range(month_weeks)], []), month_days=month_days, day_backgrounds=['white'] * len(month_days), )) djia_data = [(dj_date, DJIA) for (dj_date, DJIA) in djia_data_lst if dj_date.year == year and dj_date.month == month] nasdaq_data = [(nas_date, NASDAQCOM) for (nas_date, NASDAQCOM) in nasdaq_data_lst if nas_date.year == year and nas_date.month == month] sp500_data = [(sp500_date, SP500) for (sp500_date, SP500) in sp500_data_lst if sp500_date.year == year and sp500_date.month == month] holidays = [(holiday_date, Holiday) for (holiday_date, Holiday) in holiday_lst if holiday_date.year == year and holiday_date.month == month] twitter_data = [ (twitter_date, topics) for (twitter_date, topics) in twitter_data_lst if twitter_date.year == year and twitter_date.month == month ] nyt_data = [(nyt_date, headlines) for (nyt_date, headlines) in nyt_data_lst if nyt_date.year == year and nyt_date.month == month] approval_data = [ (approval_date, approve_estimate) for (approval_date, approve_estimate) in approval_data_lst if approval_date.year == year and approval_date.month == month ] approval_data.sort() generic_dem = [(generic_date, dem_estimate) for (generic_date, dem_estimate) in generic_dem_lst if generic_date.year == year and generic_date.month == month ] generic_dem.sort() generic_rep = [(generic_date, rep_estimate) for (generic_date, rep_estimate) in generic_rep_lst if generic_date.year == year and generic_date.month == month ] generic_rep.sort() colors_djia = [DJIA for _, DJIA in djia_data] colors_sp500 = [SP500 for _, SP500 in sp500_data] colors_nasdaq = [NASDAQCOM for _, NASDAQCOM in nasdaq_data] for i in range(len(colors_djia) - 1): avg = np.mean([colors_djia[i], colors_sp500[i], colors_nasdaq[i]]) if 0 < avg <= 11000: colors_djia[i] = '#E52700' elif 11000 < avg <= 11100: colors_djia[i] = '#E33A00' elif 11100 < avg <= 11200: colors_djia[i] = '#E14C00' elif 11200 < avg <= 11300: colors_djia[i] = '#DF5E00' elif 11300 < avg <= 11400: colors_djia[i] = '#DD6F00' elif 11400 < avg <= 11500: colors_djia[i] = '#DB8000' elif 11500 < avg <= 11600: colors_djia[i] = '#D99100' elif 11600 < avg <= 11700: colors_djia[i] = '#D7A100' elif 11700 < avg <= 11800: colors_djia[i] = '#D5B100' elif 11800 < avg <= 11900: colors_djia[i] = '#D3C100' elif 11900 < avg <= 12000: colors_djia[i] = '#D1D000' elif 12000 < avg <= 12100: colors_djia[i] = '#BECF00' elif 12200 < avg <= 12300: colors_djia[i] = '#ABCD00' elif 12300 < avg <= 12400: colors_djia[i] = '#99CB00' elif 12400 < avg <= 12500: colors_djia[i] = '#87C900' elif 12500 < avg <= 12600: colors_djia[i] = '#75C700' elif 12500 < avg <= 12600: colors_djia[i] = '#64C500' else: colors_djia[i] = '#53C300' holiday_source = ColumnDataSource(data=dict( month_djia=[DJIA for _, DJIA in djia_data], month_nasdaq=[NASDAQCOM for _, NASDAQCOM in nasdaq_data], month_sp500=[SP500 for _, SP500 in sp500_data], month_twitter=[topics for _, topics in twitter_data], month_holidays=[Holiday for _, Holiday in holidays], nyt_days=[day_names[weekday(nyt_date)] for nyt_date, _ in nyt_data], nyt_weeks=['0'] + [ str((weekday(nyt_date.replace(day=1)) + nyt_date.day) // 7) for nyt_date, _ in nyt_data ], month_nyt=[headlines for _, headlines in nyt_data], month_approval=[ approve_estimate for _, approve_estimate in approval_data ], month_generic_dem=[dem_estimate for _, dem_estimate in generic_dem], month_generic_rep=[rep_estimate for _, rep_estimate in generic_rep], day_backgrounds=colors_djia, )) xdr = FactorRange(factors=list(day_names)) ydr = FactorRange( factors=list(reversed([str(week) for week in range(month_weeks)]))) x_scale, y_scale = CategoricalScale(), CategoricalScale() plot = Plot(x_range=xdr, y_range=ydr, x_scale=x_scale, y_scale=y_scale, plot_width=plot_wid, plot_height=plot_ht) plot.title.text = month_names[month] + " " + str(year) plot.title.text_font_size = "14pt" plot.title.text_color = "black" plot.title.offset = 25 plot.min_border_left = 5 plot.min_border_top = 5 plot.min_border_bottom = 190 plot.border_fill_color = "white" plot.background_fill_alpha = 0.5 plot.border_fill_alpha = 0.3 rect = Rect(x="days", y="weeks", width=0.9, height=0.9, fill_color="day_backgrounds", line_color="silver") plot.add_glyph(source, rect) rect = Rect(x="nyt_days", y="nyt_weeks", width=0.9, fill_color="day_backgrounds", height=0.9) rect_renderer = plot.add_glyph(holiday_source, rect) text = Text(x="days", y="weeks", text="month_days", text_align="center", text_baseline="middle") plot.add_glyph(source, text) xaxis = CategoricalAxis() xaxis.major_label_text_font_size = "10pt" xaxis.major_label_standoff = 0 xaxis.major_tick_line_color = None xaxis.axis_line_color = None plot.add_layout(xaxis, 'above') TOOLTIPS = """ <div style="height:100%; max-width:300px; min-width:200px;background-color: aliceblue; position:relative;"> <div> <span style="font-size: 17px; font-weight: bold;"> Holiday: @month_holidays</span><br> <span style="font-size: 15px; font-weight: bold; color: darkgrey;"> Trump Approval Rating: @month_approval{0,0.0}%</span><br> <span style="font-size: 15px; font-weight: bold; color: blue;"> Generic Democrat: @month_generic_dem{0,0.0}%</span><br> <span style="font-size: 15px; font-weight: bold; color: red;"> Generic Republican: @month_generic_rep{0,0.0}%</span><br> <span style="font-size: 17px; font-weight: bold;"> NASDAQ: @month_nasdaq{0,0.00}</span><br> <span style="font-size: 17px; font-weight: bold;"> DJIA: @month_djia{0,0.00}</span><br> <span style="font-size: 17px; font-weight: bold;">S&P500: @month_sp500{0,0.00}</span><br> </div> <div> <img src="/static/img/nyt_logo.png" height="15" width="15" style="float: left;"></img> </div> <div> <span style="font-size: 17px; font-weight: bold;">NYT Headlines:</span> <span style="font-size: 15px;">@month_nyt</span> </div> <div> <img src="/static/img/twitter_logo.png" height="15" width="15" style="float: left;"></img> </div> <div> <span style="font-size: 17px; color:blue; font-weight: bold;">Trending Tweets:</span> <span style="font-size: 15px; color:blue;">@month_twitter</span> </div> </div> """ hover_tool = HoverTool(renderers=[rect_renderer], tooltips=TOOLTIPS) # hover_tool = HoverTool(renderers=[rect_renderer], tooltips=[("Holiday", "@month_holidays"),("DJIA", "@month_djia{0,0.00}"), # ("NASDAQ", "@month_nasdaq{0,0.00}"),("S&P500", "@month_sp500{0,0.00}"),("NYT Headlines", "@month_nyt"),("Trending Tweets","@month_twitter")]) plot.tools.append(hover_tool) return plot