def __format_calendar(self, year, month, rows): """ カレンダー形式のレスポンスに整形 """ # 日曜始まり cl = TextCalendar(firstweekday=6) # 週単位での日付と曜日を取得 weeks = cl.monthdays2calendar(year, month) res = [] for week in weeks: week_data = [] for day in week: current_date, weekday = day data = next( (row for row in rows if row['sales_day'] == current_date), None) is_saturday = True if weekday == self.SATURDAY else False is_sunday = True if weekday == self.SUNDAY else False sales_day = None total_price = None if data is not None: sales_day = data['sales_date'].strftime('%Y-%m-%d') total_price = int(data['total_price']) week_data.append({ 'sales_date': current_date, 'sales_day': sales_day, 'amount': total_price, 'is_saturday': is_saturday, 'is_holiday': is_sunday, 'daily_sales_url': '' }) res.append(week_data) return res
def __init__(self, root): self.root = root self.root.title(APP_NAME) self.instance = TextCalendar() self.root.resizable(False, False) self.init_gui() self.update_display() self.root.mainloop()
def __init__(self, root): self.root = root self.root.title(APP_NAME) self.instance = TextCalendar() self.root.resizable(False, False) self.init_gui() self.update_display() print(self.display_widget.winfo_width(), self.display_widget.winfo_height()) self.root.mainloop()
def get_calendar(channel, date, links=True): calendar = TextCalendar(firstweekday=6).formatmonth(date.year, date.month) if not links: return calendar calendar = re.sub(r'\b(\d{1,2})\b', lambda m: day_link(channel, date, m), calendar) next_month = add_one_month(date) prev_month = subtract_one_month(date) parts = [ '<a href="/{0}/{1}"><</a>'.format(channel, prev_month.isoformat()), '{}'.format(date.strftime("%B %Y").center(18)), '<a href="/{0}/{1}">></a>'.format(channel, next_month.isoformat()), '\n{}'.format('\n'.join(calendar.split('\n')[1:-1])) ] return ''.join(parts)
def generating_calendar_content(self): """ return:: None """ for i in range(1, 13): self._content.append(TextCalendar(firstweekday=0).formatmonth(int(self.title), i)) self._calendar_pages.append(len(self._content)) for k in Calendar().itermonthdates(int(self.title), i): if k.month == i: self._content.append(str(k))
def __init__(self, parent, values): self.values = values self.parent = parent self.cal = TextCalendar(calendar.SUNDAY) self.year = datetime.date.today().year self.month = datetime.date.today().month self.yearSelected = self.year self.monthSelected = self.month self.daySelected = 1
def get_month_ary(year: int, month: int) -> list: """Get the formatted month as a list of lists""" c = TextCalendar(6) # to make week start on Sunday month_str = c.formatmonth(year, month) weeks = month_str.split('\n') title = weeks[0].strip() weeks = weeks[1:] month = [title] for week in weeks: week_list_stripped = week.strip() week_list_split_filtered = list(filter(None, week_list_stripped.split(' '))) month.append(week_list_split_filtered) if not month[-1]: month.pop() return month[:]
def get_next_day(self): """ Find if there is possible next day If the possible next day is not out of range of the month's days, returns its day entry if exists, else will returns a simple 'datetime.date object'. The return will allways be a tuple containing the object and the resolved form's url. Finally if there is no possible next day, returns None. """ calendar = TextCalendar() # Get available days from reduced calendar's datas month_days = [item for sublist in calendar.monthdayscalendar(self.year, self.month) for item in sublist if item] month_range = (month_days[0], month_days[-1]) # Next day is out of range for current month if self.day+1 > month_days[-1]: return None # Next day is in range, try to find if its day entry allready exists next_day = datetime.date(self.year, self.month, self.day+1) try: obj = self.datebook.dayentry_set.get(activity_date=next_day) except DayEntry.DoesNotExist: return next_day, reverse('datebook:day-add', kwargs={ 'author': self.author, 'year': next_day.year, 'month': next_day.month, 'day': next_day.day, }) else: return obj, reverse('datebook:day-edit', kwargs={ 'author': self.author, 'year': next_day.year, 'month': next_day.month, 'day': next_day.day, }) return None
def get_month_ary(year: int, month: int) -> list: """Get the formatted month as a list of lists""" c = TextCalendar(6) # to make week start on Sunday month_str = c.formatmonth(year, month) weeks = month_str.split('\n') title = weeks[0].strip() weeks = weeks[1:] month = [title] for week in weeks: week_list_stripped = week.strip() week_list_split_filtered = list( filter(None, week_list_stripped.split(' '))) month.append(week_list_split_filtered) if not month[-1]: month.pop() return month[:]
def calendar(): settings = sys.argv now = datetime.now() year = now.year month = now.month # print(settings, year, month) numArg = len(sys.argv) try: if numArg > 1: if numArg > 2: print( TextCalendar(6).prmonth( int(settings[2][1:len(settings[2]) - 1]), int(settings[1]))) else: print(TextCalendar(6).prmonth(year, int(settings[1]))) else: print(TextCalendar(6).prmonth(year, month)) except: # analogous to the try/catch blocks in JS print( "\"Please input parameters in the format '14_cal.py month [year]'\"" )
def horizontalImages(self): today = date.today() image = Image.new("1", size=(self.width, self.height), color=255) imagey = Image.new("1", size=(self.width, self.height), color=255) cal = TextCalendar().formatmonth(today.year, today.month) draw = ImageDraw.Draw(image) drawy = ImageDraw.Draw(imagey) draw.text((50, 10), today.strftime("%b"), font=self.font_heading) draw.text((30, 70), today.strftime("%d"), font=self.font_big) draw.text((50, 220), today.strftime("%Y"), font=self.font_heading) drawy.text((210, 30), cal, font=self.font_cal) draw.text((210, 220), today.strftime("%A"), font=self.font_heading) drawy.text((50, 300), "\n".join(textwrap.wrap(getQuote())), font=self.font_quote) return image, imagey
def verticalImages(self): today = date.today() image = Image.new("1", size=(self.width, self.height), color=255) imagey = Image.new("1", size=(self.width, self.height), color=255) cal = TextCalendar().formatmonth(today.year, today.month) draw = ImageDraw.Draw(image) drawy = ImageDraw.Draw(imagey) draw.text((50, 10), today.strftime("%b %d %Y"), font=self.font_heading) drawy.text((50, 80), today.strftime("%A"), font=self.font_heading) self.makeCalImg() calimg = Image.open("./cal.jpg").convert("1") image.paste(calimg, (40, 160)) # draw.text((40, 160), cal, font = self.font_cal) # drawy.text((50, 400), "\n".join(textwrap.wrap(getQuote(), width=30)), font = self.font_quote) self.makeImage(imagey) return image, imagey
def main(): current_year = current_date.year current_month = current_date.month current_month_name = current_date.strftime("%B") current_weekday = current_date.weekday() current_weekday_name = current_date.strftime("%A") cal = TextCalendar().monthdatescalendar(current_year, current_month) events_dict = load_json("events.json") dates = [] message = [] for week in cal: for day in week: if day.month == current_month and day.weekday() == current_weekday: dates.append(day) if current_month_name in events_dict \ and current_weekday_name in events_dict[current_month_name]: events = events_dict[current_month_name][current_weekday_name] if "First" in events and events["First"]: if current_date.date() == dates[0]: message.append(events["First"]) if "Last" in events and events["Last"]: if current_date.date() == dates[-1]: message.append(events["Last"]) if "Every" in events and events["Every"]: message.append(events["Every"]) if message: send_text(', '.join(message)) else: print("No notifications")
events.append( (calname, component)) events.sort(key = lambda t : t[1]['DTEND'].dt) output_string = '' shorthands = [ '🌞', '🐒', '🇹', '💍', '🌩️', '🍟', '📡' ] calendar_lines = TextCalendar(firstweekday=6).formatmonth( theyear = now.year, themonth = now.month, ).strip().split('\n') calendar_lines[1] = ' '.join(shorthands) k = now.isoweekday() % 7 d = now.day # that means the 1st was on (k-d+1)'th day of week # so the calendar starts with (k-d+1) extra days row = (d + ((k-d+1)%7) - 1) // 7 # 0-indexed row number to get calendar_lines[row+2] = calendar_lines[row+2][:3*k] \ + '💚' + calendar_lines[row+2][3*k+2:] calendar_text = '\n'.join(calendar_lines) embed = DiscordEmbed( title = options.get('title', 'Calendar'), description = f"Generated on {now.strftime('%A, %B %d, %H:%M')}" \ + "\n" + f"Time zone: {tz.zone}" + "\n" \
# モジュールからクラスを指定してインスタンスを生成する際はModule名.Class名が必要と言ったなあれは嘘だ # 正確には、クラスを指定してimportする記法が存在する、よってそれを使用すれば一々Module名を指定する必要がなくなる # 以下にその例を示す # calenderModuleからTextCalendarクラスのみをimportする from calendar import TextCalendar # fromでModule名とクラス名を指定してインポートしているのでインスタンス生成時に改めてModule名を指定する必要はない cal = TextCalendar(6) cal.prmonth(2017,5) # !ただし、複数のモジュールからimportする場合や独自クラスを作成している場合はクラス名の重複に注意! # クラス名の重複が起きた場合は、古いクラスから上書きされていく # FIXME 月日を標準入力から指定することができるように書き換えること import calendar # import Calnedar.TextCalendar
from calendar import TextCalendar year = int(input("年を入力してください: ")) month = int(input("月を入力してください: ")) cal = TextCalendar(6) cal.prmonth(year, month) cal_str = cal.formatmonth(year, month) print(cal_str)
module may be helpful for this. - If the user specifies one argument, assume they passed in a month and render the calendar for that month of the current year. - If the user specifies two arguments, assume they passed in both the month and the year. Render the calendar for that month and year. - Otherwise, print a usage statement to the terminal indicating the format that your program expects arguments to be given. Then exit the program. """ import sys from calendar import TextCalendar from datetime import datetime cal = TextCalendar() UsageError = Exception(""" Please provide a month and then year, as numbers, e.g. python3 14_cal.py 5 2019 Or provide nothing at all to get the current month's calendar. """) try: if len(sys.argv) == 1: query_month = datetime.today().month query_year = datetime.today().year elif len(sys.argv) == 2: query_month = int(sys.argv[1]) query_year = datetime.today().year elif len(sys.argv) == 3: query_month = int(sys.argv[1])
class GUIBeeTop(GlassWindow, Observable): # messages to the observers OBS_WHEEL = 0 OBS_CLOSE = 1 OBS_MOVE = 2 OBS_MENU = 3 OBS_CLICK = 4 def __init__(self): super(GUIBeeTop, self).__init__() # flag indicating whether this window is currently being dragged self.__is_dragging = 0 self.__drag_offset = (0, 0) self.set_icon_from_file(_config["icon"]) self.set_title("Beetop") self.set_size_request(_config["window_w"], _config["window_h"] + _config['window_eh'] * len(_config['tasks'])) self.set_position(gtk.WIN_POS_MOUSE) # self.set_decorated(False) # self.set_resizable(True) self.stick() self.connect("key-press-event", self.__on_key) self.connect("destroy", gtk.main_quit) self.connect("scroll-event", self.__on_mouse_wheel) # window moving self.connect("button-press-event", self.__on_button_press) self.connect("button-release-event", self.__on_button_release) gobject.idle_add(self.set_property, "skip-taskbar-hint", 1) gobject.idle_add(self.set_property, "skip-pager-hint", 1) # keep window below others self.connect("focus-in-event", self.__lower_window) self.connect_after("button-press-event", self.__lower_window) self.add_events(gtk.gdk.SCROLL_MASK | gtk.gdk.POINTER_MOTION_MASK | # gtk.gdk.POINTER_MOTION_HINT_MASK | gtk.gdk.BUTTON_PRESS_MASK | gtk.gdk.BUTTON_RELEASE_MASK) self.set_bg_image(_config['bg_img'], _config['bg_img_alpha']) self.update_bg() vbox_app = gtk.VBox(False, 0) self.add(vbox_app) vbox_app.show() self._show_day = None self._calendar = TextCalendar(mycal.firstweekday) self._lb_month_year = gtk.Label("") self._lb_month_year.modify_fg(gtk.STATE_NORMAL, gtk.gdk.color_parse(_config['month_year_color'])) self._lb_month_year.show() self._lb_week = CalLabel(7, 1, True) self._lb_week.show() self._lb_days = CalLabel(7, 6, True) self._lb_days.show() self._lb_uptime = gtk.Label("") self._lb_uptime.modify_fg(gtk.STATE_NORMAL, gtk.gdk.color_parse(_config['uptime_color'])) self._lb_uptime.show() self._lb_tasks = [] self._task_tooltips = [] for _ in _config['tasks']: tlab = gtk.Label("") tlab.show() self._lb_tasks.append(tlab) ttip = gtk.Tooltips() ttip.set_delay(200) self._task_tooltips.append(ttip) self._task_results = [None] * len(self._lb_tasks) vbox_app.pack_start(self._lb_month_year, False, False, 3) vbox_app.pack_start(self._lb_week, False, False, 2) vbox_app.pack_start(self._lb_days, False, False, 1) vbox_app.pack_start(self._lb_uptime, False, False, 2) for tlab in self._lb_tasks: vbox_app.pack_start(tlab, False, False, 1) self.task_fonts = [] self.task_fonts.append(pango.FontDescription(_config["task_error_font"])) self.task_fonts.append(pango.FontDescription(_config["task_norm_font"])) self.task_fonts.append(pango.FontDescription(_config["task_strong_font"])) self.task_colors = [] self.task_colors.append(_config["task_error_color"]) self.task_colors.append(_config["task_norm_color"]) self.task_colors.append(_config["task_strong_color"]) self.__popup_menu = Menu([ ["_mycal.py", self.edit_file, ["mycal.py"]], ["_beetask.py", self.edit_file, ["beetask.py"]], ["_config.json", self.edit_file, ["config.json"]], ["_README", self.edit_file, ["README"]], [], ["_Move", self.move_window, []], ["_Quit", self.__cmd_quit, []]]) # desktop.watch_bg(self.__on_bg_change) self.add_observer(self.__on_window) self.show() if _config['position_x'] == 0: _config['position_x'] = gtk.gdk.screen_width() - _config["window_w"] - 5 self.move(_config["position_x"] , _config["position_y"]) self.after_runs = 0 self._after_run() # self.move_window() def _after_run(self): today = datetime.date.today() if self._show_day != today: self._show_day = today self._set_cal() d2 = os.popen('uptime').read().strip() i = d2.rfind(', ') self._lb_uptime.set_label(d2[:i] + "\n" + d2[(i + 3):]) t = 0 for task, delay in _config['tasks']: if self.after_runs % delay == 0: self._run_task(t, task) t += 1 gobject.timeout_add(_config['interval'], self._after_run) self.after_runs += 1 def _set_cal(self): data = self._calendar.formatmonth(self._show_day.year, self._show_day.month).strip().split('\n') self._lb_month_year.set_text("%s %d" % (mycal.monthname[self._show_day.month - 1], self._show_day.year)) # ws = data[1].split() #decode error? i = 0 wd = [] for d in self._calendar.iterweekdays(): wd.append(d) week = self._lb_week.get_label(i) week.set_text(mycal.weekname[d]) week.modify_fg(gtk.STATE_NORMAL, gtk.gdk.color_parse(_config['week_color'])) i += 1 i = 0 today = datetime.date.today() cday = "%d-%d-%d" % (today.year, today.month, today.day) ym = "%d-%d" % (self._show_day.year, self._show_day.month) for dat in data[2:]: # print dat, i ds = dat.strip().split() if i == 0 and len(ds) < 7: # the first ds = [" "] * (7 - len(ds)) + ds if len(ds) < 7: # the last ds = ds + [" "] * (7 - len(ds)) for j in range(7): lday, ltip = self._lb_days.get_labeltip_at(j, i) lday.set_text(ds[j]) mday = "%s-%s" % (ym, ds[j]) if (not ds[j].isspace()) and (wd[j] in mycal.weekevent or mday in mycal.dayevent): lday.modify_fg(gtk.STATE_NORMAL, gtk.gdk.color_parse(_config['event_day_color'])) tips = [] if wd[j] in mycal.weekevent: tips.append(mycal.weekevent[wd[j]]) if mday in mycal.dayevent: tips.append(mycal.dayevent[mday]) ltip.set_tip(lday, "\n".join(tips), tip_private=None) else: lday.modify_fg(gtk.STATE_NORMAL, gtk.gdk.color_parse(_config['norm_day_color'])) ltip.set_tip(lday, "", tip_private=None) # clear if cday == mday: # lday.modify_font(font_month) lday.modify_fg(gtk.STATE_NORMAL, gtk.gdk.color_parse(_config['today_color'])) i += 1 if i < 6: # clean others for j in range(7): lday, ltip = self._lb_days.get_labeltip_at(j, i) lday.set_text("") lday.modify_fg(gtk.STATE_NORMAL, gtk.gdk.color_parse(_config['norm_day_color'])) ltip.set_tip(lday, "", tip_private=None) # clear i += 1 def _run_task(self, t, task=None): if not task: task, delay = _config['tasks'][t] self._task_results[t] = beetask.__dict__[task]() status, title, tip, _ = self._task_results[t] self._lb_tasks[t].set_label(title) if status < 0: status = -1 elif status > 0: status = 1 self._lb_tasks[t].modify_font(self.task_fonts[status + 1]) self._lb_tasks[t].modify_fg(gtk.STATE_NORMAL, gtk.gdk.color_parse(self.task_colors[status + 1])) self._task_tooltips[t].set_tip(self._lb_tasks[t], tip, tip_private=None) def edit_file(self, ifile): os.system("%s %s >/dev/null 2>&1 &" % (_config['editor'], os.path.join(sys.path[0], ifile))) # # Reacts on key presses. # def __on_key(self, src, event): key = gtk.gdk.keyval_name(event.keyval) # SPACE updates the background if (key == "space"): self.update_bg() # F10 opens the menu elif (key == "F10"): # self.update_observer(self.OBS_MENU, 0, event.time) self.move_window() # # Reacts on closing the window. # def __on_close(self, src, event): self.update_observer(self.OBS_CLOSE) # # Updates the background. # def update_bg(self, noscreenshot=0): GlassWindow.update_bg(self, noscreenshot) self.stick() # # Reacts on changes to the background image. # def __on_bg_change(self, src, cmd): self.update_bg() # # Reacts on pressing a mouse button. # def __on_button_press(self, src, event): button = event.button modifiers = event.state if (button == 1): x, y = self.get_pointer() self.update_observer(self.OBS_CLICK, x, y) if (button == 2): x, y = self.get_pointer() self.__is_dragging = 1 self.__drag_offset = (x, y) self.window.set_cursor(gtk.gdk.Cursor(gtk.gdk.FLEUR)) gobject.timeout_add(20, self.__on_move) # # Reacts on releasing a mouse button. # def __on_button_release(self, src, event): if (self.__is_dragging): self.__is_dragging = 0 self.window.set_cursor(None) self.update_bg() elif (event.button == 3): self.update_observer(self.OBS_MENU, event.button, event.time) # # Reacts on mouse wheel. # def __on_mouse_wheel(self, src, event): if (event.direction == gtk.gdk.SCROLL_UP): step = -1 elif (event.direction == gtk.gdk.SCROLL_DOWN): step = 1 else: step = 0 self.update_observer(self.OBS_WHEEL, step) # # Keeps the window below others. # def __lower_window(self, src, event): if (self.window): self.window.lower() return True # # Reacts on window events. # def __on_window(self, src, cmd, *args): if (cmd == src.OBS_WHEEL): step = args[0] m = self._show_day.month + step if m > 12: self._show_day = datetime.date(self._show_day.year + 1, 1, self._show_day.day) elif m < 1: self._show_day = datetime.date(self._show_day.year - 1, 12, self._show_day.day) else: self._show_day = datetime.date(self._show_day.year, m, self._show_day.day) self._set_cal() elif (cmd == src.OBS_CLICK): x, y = args _, ly = self._lb_month_year.get_layout_offsets() if y > ly and y < ly + 20: today = datetime.date.today() if self._show_day != today: self._show_day = today self._set_cal() else: for i in range(len(self._lb_tasks) - 1, -1, -1): lx, ly = self._lb_tasks[i].get_layout_offsets() if y >= ly: # print _config['tasks'][i] cmd = self._task_results[i] if cmd != None: cmd = self._task_results[i][-1] if x < 30 and cmd: os.system(cmd) else: self._run_task(i) # run it now break elif (cmd == src.OBS_CLOSE): self.__cmd_quit() elif (cmd == src.OBS_MOVE): x, y = args[0] print x, y # self.__config.set([conf.GEOMETRY, conf.WINDOW, conf.X], str(x)) # self.__config.set([conf.GEOMETRY, conf.WINDOW, conf.Y], str(y)) elif (cmd == src.OBS_MENU): button = args[0] etime = args[1] self.__popup_menu.popup(button, etime) # # Reacts on moving the mouse pointer. # def __on_move(self): if (self.__is_dragging): offx, offy = self.__drag_offset winx, winy = self.get_position() # print winx, winy x, y = self.get_pointer() x += winx; y += winy self.move(x - offx, y - offy) return True else: return False # # Switches to window move mode. # def move_window(self): x, y = self.get_pointer() width, height = self.window.get_size() x = max(4, min(x, width - 4)) y = max(4, min(y, height - 4)) self.__is_dragging = 1 self.__drag_offset = (x, y) gobject.timeout_add(20, self.__on_move) def __cmd_quit(self): # self.__config.save() gtk.main_quit() def main(self): gtk.main()
class CalendarApp(): """"Creating the App by passing it the root windows""" def __init__(self, root): self.root = root self.root.title(APP_NAME) self.instance = TextCalendar() self.root.resizable(False, False) self.init_gui() self.update_display() print(self.display_widget.winfo_width(), self.display_widget.winfo_height()) self.root.mainloop() def init_gui(self): self.create_year_combobox() self.create_month_combobox() self.create_display() def create_year_combobox(self): tk.Label(self.root, text='Select Year').grid(column=0, row=0) self.year_widget = ttk.Combobox( self.root, state='readonly') self.year_widget['values'] = YEAR_LIST self.year_widget.current(YEAR_LIST.index(CURRENT_YEAR)) self.year_widget.grid(column=1, row=0, padx=5, pady=6) self.year_widget.bind("<<ComboboxSelected>>", self.update_display) def create_month_combobox(self): tk.Label(self.root, text='Select Month').grid(column=2, row=0) self.month_widget = ttk.Combobox( self.root, state='readonly', ) self.month_widget['values'] = MONTH_LIST self.month_widget.current(CURRENT_MONTH - 1) self.month_widget.grid(column=3, row=0, padx=5, pady=6) self.month_widget.bind("<<ComboboxSelected>>", self.update_display) def create_display(self): self.display_widget = scrolledtext.ScrolledText( self.root, background='#3c53d1', foreground='#ffffff', width=90) self.display_widget.grid(column=0, row=2, padx=5, pady=6, columnspan=5) def update_display(self, event=None): year = int(self.year_widget.get()) self.display_widget.configure(state='normal') self.display_widget.delete('0.0', tk.END) self.display_widget.insert('0.0', self.instance.formatyear(year, 2, 2)) month = self.month_widget.get() pos = self.display_widget.search(month, '0.0') self.add_tag(month, pos) self.display_widget.see(pos) self.display_widget.configure(state='disabled') def add_tag(self, month, start_pos): end_pos = '{}+{}c'.format(start_pos, len(month)) self.display_widget.tag_add('active', start_pos, end_pos) self.display_widget.tag_config( 'active', foreground='red', background='yellow') self.add_space() def add_space(self): def hack(start_pos): a = start_pos.split('.') a[1] = str(int(a[1]) - 1) a[0] = str(int(a[0]) + 1) return '.'.join(a) start_pos = '1.0' while True: start_pos = self.display_widget.search( '\n', start_pos, stopindex='end') if not start_pos: break end_pos = '{}+{}c'.format(start_pos, 2) i_value = hack(start_pos) self.display_widget.insert(i_value, '\t') print(start_pos) start_pos = end_pos
from calendar import TextCalendar year = 0 month = 1 while True: year = abs(int(input('Enter the year: '))) if year: break while True: month = abs(int(input('Enter the month: '))) if month <= 12 and month > 0: break else: print('The number must be in range of 1 to 12') calendar = TextCalendar(firstweekday=0) calendar.prmonth(year, month)
#Example of working with Calendar import calendar from calendar import TextCalendar cal = TextCalendar() #Returns the calender for the year 2017 cal.pryear(2018) #Returns the calender for the month of Novemeber in 2017 cal.prmonth(2018, 6)
module may be helpful for this. - If the user specifies one argument, assume they passed in a month and render the calendar for that month of the current year. - If the user specifies two arguments, assume they passed in both the month and the year. Render the calendar for that month and year. - Otherwise, print a usage statement to the terminal indicating the format that your program expects arguments to be given. Then exit the program. ''' import sys from calendar import TextCalendar from datetime import datetime cal = TextCalendar() today = datetime.now() def createCalendar(month=today.month, year=today.year): return cal.formatmonth(year, month) try: dates = map(int, sys.argv[1:]) calendar = createCalendar(*dates) print('\n=====================\n') print(calendar) print('=====================\n') except ValueError: print('\nYour supplied argument(s) could not be parsed as integers.')
You are given the following information, but you may prefer to do some research for yourself. 1 Jan 1900 was a Monday. Thirty days has September, April, June and November. All the rest have thirty-one, Saving February alone, Which has twenty-eight, rain or shine. And on leap years, twenty-nine. A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400. How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)? """ from calendar import TextCalendar cl = TextCalendar() cl.setfirstweekday(6) # asigna como primer día de la semana a domingo first_sunday = 0 for year in range(1901, 2001): for month in range(1, 13): month_of_the_year = cl.monthdayscalendar( year, month) # devuelve un array del mes con arrays de las semanas if month_of_the_year[0][0] == 1: # si domingo es el primer día del mes first_sunday += 1 print(first_sunday) # [Finished in 362ms]
# Use the sys module to look for command line arguments in the `argv` list # variable. # # If the user specifies two command line arguments, month and year, then draw # the calendar for that month. # Stretch goal: if the user doesn't specify anything on the command line, show # the calendar for the current month. See the 'datetime' module. # Hint: this should be about 15 lines of code. No loops are required. Read the # docs for the calendar module closely. import sys from calendar import TextCalendar from datetime import datetime tc = TextCalendar() try: month = int(sys.argv[1]) except Exception as e: month = datetime.today().month try: year = int(sys.argv[2]) except Exception as e: year = datetime.today().year tc.prmonth(year, month)
def __init__(self): super(GUIBeeTop, self).__init__() # flag indicating whether this window is currently being dragged self.__is_dragging = 0 self.__drag_offset = (0, 0) self.set_icon_from_file(_config["icon"]) self.set_title("Beetop") self.set_size_request(_config["window_w"], _config["window_h"] + _config['window_eh'] * len(_config['tasks'])) self.set_position(gtk.WIN_POS_MOUSE) # self.set_decorated(False) # self.set_resizable(True) self.stick() self.connect("key-press-event", self.__on_key) self.connect("destroy", gtk.main_quit) self.connect("scroll-event", self.__on_mouse_wheel) # window moving self.connect("button-press-event", self.__on_button_press) self.connect("button-release-event", self.__on_button_release) gobject.idle_add(self.set_property, "skip-taskbar-hint", 1) gobject.idle_add(self.set_property, "skip-pager-hint", 1) # keep window below others self.connect("focus-in-event", self.__lower_window) self.connect_after("button-press-event", self.__lower_window) self.add_events(gtk.gdk.SCROLL_MASK | gtk.gdk.POINTER_MOTION_MASK | # gtk.gdk.POINTER_MOTION_HINT_MASK | gtk.gdk.BUTTON_PRESS_MASK | gtk.gdk.BUTTON_RELEASE_MASK) self.set_bg_image(_config['bg_img'], _config['bg_img_alpha']) self.update_bg() vbox_app = gtk.VBox(False, 0) self.add(vbox_app) vbox_app.show() self._show_day = None self._calendar = TextCalendar(mycal.firstweekday) self._lb_month_year = gtk.Label("") self._lb_month_year.modify_fg(gtk.STATE_NORMAL, gtk.gdk.color_parse(_config['month_year_color'])) self._lb_month_year.show() self._lb_week = CalLabel(7, 1, True) self._lb_week.show() self._lb_days = CalLabel(7, 6, True) self._lb_days.show() self._lb_uptime = gtk.Label("") self._lb_uptime.modify_fg(gtk.STATE_NORMAL, gtk.gdk.color_parse(_config['uptime_color'])) self._lb_uptime.show() self._lb_tasks = [] self._task_tooltips = [] for _ in _config['tasks']: tlab = gtk.Label("") tlab.show() self._lb_tasks.append(tlab) ttip = gtk.Tooltips() ttip.set_delay(200) self._task_tooltips.append(ttip) self._task_results = [None] * len(self._lb_tasks) vbox_app.pack_start(self._lb_month_year, False, False, 3) vbox_app.pack_start(self._lb_week, False, False, 2) vbox_app.pack_start(self._lb_days, False, False, 1) vbox_app.pack_start(self._lb_uptime, False, False, 2) for tlab in self._lb_tasks: vbox_app.pack_start(tlab, False, False, 1) self.task_fonts = [] self.task_fonts.append(pango.FontDescription(_config["task_error_font"])) self.task_fonts.append(pango.FontDescription(_config["task_norm_font"])) self.task_fonts.append(pango.FontDescription(_config["task_strong_font"])) self.task_colors = [] self.task_colors.append(_config["task_error_color"]) self.task_colors.append(_config["task_norm_color"]) self.task_colors.append(_config["task_strong_color"]) self.__popup_menu = Menu([ ["_mycal.py", self.edit_file, ["mycal.py"]], ["_beetask.py", self.edit_file, ["beetask.py"]], ["_config.json", self.edit_file, ["config.json"]], ["_README", self.edit_file, ["README"]], [], ["_Move", self.move_window, []], ["_Quit", self.__cmd_quit, []]]) # desktop.watch_bg(self.__on_bg_change) self.add_observer(self.__on_window) self.show() if _config['position_x'] == 0: _config['position_x'] = gtk.gdk.screen_width() - _config["window_w"] - 5 self.move(_config["position_x"] , _config["position_y"]) self.after_runs = 0 self._after_run()
month and render the calendar for that month of the current year. - If the user specifies two arguments, assume they passed in both the month and the year. Render the calendar for that month and year. - Otherwise, print a usage statement to the terminal indicating the format that your program expects arguments to be given. Then exit the program. """ import sys from calendar import TextCalendar from datetime import datetime current_year = datetime.now().year cal_input = input("Please input year and month (XXXX XX): ").strip().split(" ") if len(cal_input) < 2 and len(cal_input) > 0: TextCalendar().prmonth(current_year, int(cal_input[0])) else: TextCalendar().prmonth(int(cal_input[0]), int(cal_input[1])) print(current_year) print(cal_input)
- If the user specifies one argument, assume they passed in a month and render the calendar for that month of the current year. - If the user specifies two arguments, assume they passed in both the month and the year. Render the calendar for that month and year. - Otherwise, print a usage statement to the terminal indicating the format that your program expects arguments to be given. Then exit the program. """ import sys from calendar import TextCalendar from datetime import date args = sys.argv cal = TextCalendar() if len(args) > 3: print('''Please provide one of the following: \n(a): no arguments, to get the current month \n(b): a single month argument, with jan = 1, to get that month of the current year \n(c): a month and a year argument, to get a calendar for that month year combination''' ) else: try: if len(args) == 1: date = date.today() year = date.year month = date.month elif len(args) == 2:
# -*- coding: utf-8 -*- from calendar import TextCalendar, HTMLCalendar tc = TextCalendar(firstweekday=6) # print [tc.prmonth(x,y) for x in range(2010,2011) for y in range(1,13)] for x in range(2010, 2011): for y in range(1, 13): tc.prmonth(x, y) # f = lambda x : x +10 # print map(f,range(10)) # f = lambda x,y : x * y # list = [] # list.append(f) # print list # print list[0](range(10),2) # # print reduce(f,range(1,10)) # f = lambda x : x < 5 # print filter(f,range(10)) # lambda x+y : x,y for x,y in (range(2016,2017) ,range(1,13)) # class test(): # def __init__(self,name = "self name"): # self.name = name # def printname(self,name = "self name"): # if name is None: # name = self.name
Note: the user should provide argument input (in the initial call to run the file) and not prompted input. Also, the brackets around year are to denote that the argument is optional, as this is a common convention in documentation. This would mean that from the command line you would call `python3 14_cal.py 4 2015` to print out a calendar for April in 2015, but if you omit either the year or both values, it should use today’s date to get the month and year. """ import sys import calendar from calendar import TextCalendar from datetime import datetime print(len(sys.argv)) cal = TextCalendar() if len(sys.argv) == 1: cal.prmonth(theyear=2020, themonth=6) elif len(sys.argv) == 2: month = int(sys.argv[1]) cal.prmonth(theyear=2020, themonth=month) elif len(sys.argv) == 3: month = int(sys.argv[1]) year = int(sys.argv[2]) cal.prmonth(theyear=year, themonth=month) elif len(sys.argv) > 3: print('Too many inputs')
def asciiMonth(year: int = today.year, month: int = today.month): return ("''%s''" % i for i in TextCalendar(0).formatmonth(year, month).split('\n'))
def on_domination(self, room, *args): calendar = TextCalendar() self.send_message(room, calendar.formatmonth(2020, 1))
print(calendar.monthrange(2021,10)) print(calendar.monthcalendar(2019, 10)) print(calendar.prmonth(2021, 10)) print(calendar.prcal(2021)) print(calendar.day_name[0]) print(calendar.day_abbr[0]) print(calendar.month_name[1]) print(calendar.month_abbr[1]) print('--------------------------------') c = Calendar() print(list(c.itermonthdates(2021, 7))) print(list(c.itermonthdays2(2020, 7))) print(list(c.itermonthdays3(2021, 7))) print(list(c.itermonthdays4(2021, 7))) print('--------------------------------') tx = TextCalendar() print(tx.formatmonth(2021, 9)) print(tx.prmonth(2021, 9)) print(tx.formatyear(2021)) print(tx.pryear(2021)) print('---------------------------------') hc = HTMLCalendar() print(hc.formatmonth(2021, 10)) print(hc.formatyear(2021)) print(hc.formatyearpage(2021))
#! env python """ Very simply emulate UNIX cal program. """ from calendar import TextCalendar from datetime import datetime import sys yearly = False args=sys.argv[1:] if args: if len(args)>1: month, year = int(args[0]), int(args[1]) else: yearly = True year = int(args[0]) else: now=datetime.now() month, year = now.month, now.year cal=TextCalendar() if yearly: cal.pryear(year) else: cal.prmonth(year, month)
#Example of working with Calendar import calendar from calendar import TextCalendar cal = TextCalendar() #Returns the calender for the year 2017 cal.pryear(2017) #Returns the calender for the month of Novemeber in 2017 cal.prmonth(2017, 11)
""" import sys from calendar import TextCalendar from datetime import datetime ERROR_MSG = 'Invalid arguments (expected numbers in format "[month] [year]")' START_DAY = 6 # Start weeks on Sunday console_args = sys.argv[1:] try: arg_count = len(console_args) if arg_count == 0: present_datetime = datetime.now() month = present_datetime.month year = present_datetime.year TextCalendar(START_DAY).prmonth(year, month) elif arg_count == 1: month = console_args[0] year = datetime.now().year TextCalendar(START_DAY).prmonth(year, int(month)) elif arg_count == 2: # pylint: disable=unbalanced-tuple-unpacking month, year = console_args TextCalendar(START_DAY).prmonth(int(year), int(month)) else: raise Exception("") except Exception as error: print(ERROR_MSG if error.__str__() == "" else f"\nTrace:\n'{error}'")
from calendar import TextCalendar year = int(input("年を入力:")) month = int(input("月を入力:")) cal = TextCalendar(6) cal.prmonth(year, month)