def cria_linha_semana(self): c = Calendar(firstweekday=6) for i in c.iterweekdays(): box = BoxLayout() lbl_dia_semana = Label(text=self.dia_semana[i], size_hint=(1, 0.5), color=(0, 0, 0, 1)) box.add_widget(lbl_dia_semana) self.ids.datas.add_widget(box) for i in c.iterweekdays(): self.ids.datas.add_widget(BoxLayout(size_hint=(0.2, 0.2)))
def week_sales(self,farm): '''This function returns the weekly deals''' date = datetime.date.today() orders = PurchaseOrder.objects.order_week(farm=farm,date=date) products_order=PurchaseOrder.objects.product_order_week(farm=farm,orders=orders) total_products = products_order[0]['total'] products = products_order[1] sales_day=[] count_sales=[] total_day=0 cal = Calendar() days = list(cal.iterweekdays()) for day in days: sales_day.append(0) count_sales.append(0) for order in orders: order_day=order.date.isocalendar()[2] total = order.total_order t_products = order.quantity for day in days: if day==order_day: if sales_day[day]!=0: price = sales_day[day]+total sales_day[day]=price total_day+=total count = count_sales[day] count_sales[day]=(count+t_products) else: total_day+=total sales_day[day]=total_day count_sales[day]=(t_products) break data = {'values':sales_day, 'count':count_sales, 'total_day':total_day, 'total_products':total_products, 'products':products} return data
def calc_month_leave_accnt(db, empid, month=datetime.date.today().month, year=datetime.date.today().year): leaves = get_leaves(db, empid, month, year) cal = Calendar() working_days = [w for w in cal.iterweekdays()] total_working_days = len(working_days) + len(get_working_days(db)) - len(get_holidays(db)) total_leaves = (0, len(leaves) - 2)[len(leaves) > 2] total_pay_days = total_working_days - total_leaves return {'working_days':total_working_days, 'total_leaves':total_leaves}
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 WeekCal(IntervalModule): """ Displays the days of the current week as they would be represented on a calendar sheet, with the current day highlighted. By default, the current day of week is displayed in the front, and the month and year are displayed in the back. Example: ``Sat 16 17 18 19 20[21]22 May 2016`` """ settings = ( ("startofweek", "First day of the week (0 = Monday, 6 = Sunday), defaults to 0."), ("prefixformat", "Prefix in strftime-format"), ("suffixformat", "Suffix in strftime-format"), ("todayhighlight", "Characters to highlight today's date"), ) startofweek = 0 interval = 30 prefixformat = "%a" suffixformat = "%b %Y" todayhighlight = ("[", "]") def __init__(self, *args, **kwargs): IntervalModule.__init__(self, *args, **kwargs) self.cal = Calendar(self.startofweek) def run(self): today = date.today() yesterday = today - timedelta(days=1) outstr = today.strftime(self.prefixformat) + " " weekdays = self.cal.iterweekdays() if today.weekday() == self.startofweek: outstr += self.todayhighlight[0] else: outstr += " " nextweek = False # keep track of offset if week doesn't start on monday for w in weekdays: if w == 0 and self.startofweek != 0: nextweek = True if nextweek and today.weekday() >= self.startofweek: w += 7 elif not nextweek and today.weekday() < self.startofweek: w -= 7 weekday_offset = today.weekday() - w weekday_delta = timedelta(days=weekday_offset) weekday = today - weekday_delta if weekday == yesterday: outstr += weekday.strftime("%d") + self.todayhighlight[0] elif weekday == today: outstr += weekday.strftime("%d") + self.todayhighlight[1] else: outstr += weekday.strftime("%d ") outstr += " " + today.strftime(self.suffixformat) self.output = { "full_text": outstr, "urgent": False, }
def main(): conf = TinyCalConfig.parse_conf(CALRCS) args = parser.parse_args() border_args = args.border args.border = None args.border_style = None args.border_weld = None for i in border_args: if i in ('full', 'basic', 'off', 'false'): args.border = i elif i in ('ascii', 'single', 'bold', 'double'): args.border_style = i elif i in ('weld', 'noweld'): args.border_weld = (i == 'weld') # Merge args and conf in-place into conf for k in vars(conf): if k in vars(args) and getattr(args, k) is not None: setattr(conf, k , getattr(args, k)) if conf.border == 'true': conf.border = 'full' elif conf.border == 'false': conf.border = 'off' if conf.color_today_wk == TinyCalConfig.color_today_wk.default: # If today.wk.color is not configured, and wk.color.fg is configured # Re-assign today.wk.color to a brighter version of wk.color if conf.color_wk.fg != None and conf.color_wk.bg == None: conf.color_today_wk = conf.color_wk.upper() else: conf.color_today_wk = conf.color_wk date_marks = {} if (args.color == 'never') or (args.color == 'auto' and not stdout.isatty()): # Disable coloring for k in vars(conf): if k.startswith('color_'): setattr(conf, k, Color('')) elif conf.marks: # Read date marking file try: with open(expanduser(conf.marks)) as marks_file: for line in marks_file: m = date_mark_regex.match(line.strip()) if not m: # Silently ignore invalid lines continue mark_date, mark_color = date(*map(int, m.group(1).split('/'))), m.group(2) try: date_marks[mark_date] = Color(mark_color) except ValueError: pass except FileNotFoundError: print('Warning: Mark file "{}" does not exist'.format(conf.marks), file=stderr) calendar = Calendar(MONDAY if conf.start_monday else SUNDAY) monthdates = calendar.monthdatescalendar today = args.today if args.today else date.today() today_wk = calculate_week_of_the_year(monthdates(today.year, 1)[0][0], today) # Calculate display range (from which month to which month) if args.year is not None and args.month is None: month_leading_dates = [date(args.year, month, 1) for month in range(1, 13)] else: year = args.year or today.year month = args.month or today.month before, after = (1, 1) if args.a1b1 else (conf.before, conf.after) month_leading_dates = calculate_month_range(before, after, year, month) # Create TinyCalRenderer object for rendering renderer = TinyCalRenderer(conf) # Colors are calculated *outside* the renderer # It's for contiguous mode def colorize_weekday(idx): color_name = 'color_weekday_%s' % weekday_codes[idx] color = getattr(conf, color_name) string = LANG[conf.lang]['weekday'][idx] return color(string) + conf.color_weekday.code if color else string weekday_title = conf.color_weekday(' '.join(map(colorize_weekday, calendar.iterweekdays()))) def colorize_wk(wk, contain_today=False): if isinstance(wk, int): if contain_today: c = conf.color_today_wk else: c = conf.color_wk return c('{:>2}'.format(wk)) return conf.color_wk(wk) wk_title = colorize_wk(LANG[conf.lang]['weekday'][-1]) month_range = [ld.month for ld in month_leading_dates] month_abbr = {} for m in range(1, 13): month_abbr[m] = (LANG[conf.lang].get('month_abbr') or LANG[conf.lang]['month'])[m].split() + [''] * 5 def colorize_day(day): if (not args.cont and day.month != ld.month) or (args.cont and day.month not in month_range): c = (conf.color_fill) if (conf.fill) else (lambda s: ' ') else: if day == today: c = conf.color_today elif day in date_marks: c = date_marks[day] else: c = getattr(conf, 'color_%s' % weekday_codes[day.weekday()]) return c('{:>2}'.format(day.day)) def get_month_abbr(month): if month not in month_range: return '' else: return month_abbr[month].pop(0) if args.cont: # For contiguous mode, only 1 Cell obj needed cells = [Cell(conf)] f = month_leading_dates[0] t = month_leading_dates[-1] if f == t: cells[0].title = '{m} {y}'.format(m=LANG[conf.lang]['month'][f.month], y=f.year) def get_month_abbr(month): return '' else: cells[0].title = '{}/{:02} ~ {}/{:02}'.format(f.year, f.month, t.year, t.month) cells[0].weekday_title = weekday_title cells[0].wk_title = wk_title else: # For non-contiguous mode, every month has its own Cell obj cells = [] for ld in month_leading_dates: cell = Cell(conf) cell.title = '{m} {y}'.format(m=LANG[conf.lang]['month'][ld.month], y=ld.year) cell.weekday_title = weekday_title cell.wk_title = wk_title cells.append(cell) def get_month_abbr(month): return '' # Put the days into cells, and cells into renderer last_cell = None last_week_leading_date = None for ld in month_leading_dates: for week in monthdates(ld.year, ld.month): # calculate week number if args.cont and ld.month != week[-1].month and ld.year != today.year: # Edge case, sometimes wk53 needs to be changed to wk01 wk = calculate_week_of_the_year(monthdates(week[-1].year, 1)[0][-1], week[-1]) else: # Normal case wk = calculate_week_of_the_year(monthdates(ld.year, 1)[0][0], week[0]) # Highlight current week if (not args.cont and today.month != ld.month) or (args.cont and today.month not in month_range): wk_contain_today = False else: wk_contain_today = today in week # Dont append days into the same cell twice (ok for different cell) if (last_cell, last_week_leading_date) != (cells[0], week[0]): cells[0].append( wk=colorize_wk(wk, contain_today=wk_contain_today), days=' '.join([colorize_day(day) for day in week]), month=get_month_abbr(week[-1].month), ) last_week_leading_date = week[0] last_cell = cells[0] if len(cells) > 1: renderer.append(cells.pop(0)) assert len(cells) == 1 renderer.append(cells[0]) print(renderer.render())
from calendar import Calendar, TextCalendar, HTMLCalendar, calendar cal = Calendar() iter = cal.iterweekdays() for i in iter: print(i) #cal.TextCalendar() html_cal = HTMLCalendar() code = html_cal.formatmonth(2017, 12, False) code = html_cal.formatyear(2017, 6) # in HTML Format! code = html_cal.formatyearpage(2017, encoding='UTF-8') code = calendar(2017) # In text ! print(code)
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
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))
# Created by nijianfeng at 18/6/17 import time import calendar from calendar import Calendar # http://www.runoob.com/python3/python3-date-time.html # 时间操作 localtime = time.localtime(time.time()) print("本地时间为 :", time.asctime(localtime)) print("本地时间为 :", localtime) # 格式化成2016-03-20 11:45:39形式 print(time.strftime("%Y-%m-%d %H:%M:%S", localtime)) # 格式化成Sat Mar 28 22:24:24 2016形式 print(time.strftime("%a %b %d %H:%M:%S %Y", localtime)) # 将格式字符串转换为时间戳 print( time.mktime( time.strptime("Sat Mar 28 22:24:24 2016", "%a %b %d %H:%M:%S %Y"))) # 日历操作 print() cal_str = calendar.month(2018, 6) print("以下输出2018年6月份的日历:\n", cal_str) cal = Calendar() print(",".join([str(v) for v in cal.iterweekdays()])) # 是否闰年 print() print(calendar.isleap(2018))