def monthcalendar(year,month): pYear, pMonth = getPreviousMonth(year,month) nYear, nMonth = getNextMonth(year,month) previous_month = calendar.monthcalendar(pYear, pMonth) next_month = calendar.monthcalendar(nYear, nMonth) this_month = calendar.monthcalendar(year,month) this_month = [[(d and '%d/%02d/%02d' % (year,month,d) or d) for d in w] for w in this_month] # we know calendar.monthcalendar will # only return previous_month dates in the first week first_week = this_month[0] # and next_month dates in the last week last_week = this_month[-1] # Add previous_month days while 0 in first_week: index = first_week.index(0) first_week[index] = '%d/%02d/%02d' % (pYear, pMonth, previous_month[-1][index]) # Add next_month days while 0 in last_week: index = last_week.index(0) last_week[index] = '%d/%02d/%02d' % (nYear, nMonth, next_month[0][index]) return this_month
def calendar_(): cal = calendar.month(2017, 6) # by default w=2 l=1 print cal # 2017年6月份日历 print '--------------------' # calendar内置函数 #calendar of year 2017: c=distance(month); l=line(week); w=distance(day) print calendar.calendar(2017, w=2, l=1, c=6) #lenth(line)= 21* W+18+2* C print calendar.firstweekday() # start weekday, 0 by default, i.e. Monday # calendar.setfirstweekday(weekday) # 0(Monday) to 6(Sunday) print calendar.isleap(2017) # return True or False print calendar.leapdays(2000, 2016) # number of leap years between year 1 and year 2 print calendar.month(2017, 6) print calendar.monthcalendar(2017, 6) print calendar.monthrange(2017, 6) # return (a, b) a=starting weekday b=days in month calendar.prcal(2017, w=2, l=1, c=4) # equals to print calendar.calendar(2017, w=2, l=1, c=4) calendar.prmonth(2017, 6) # equals to print calendar.month(2017, 6) print calendar.timegm(time.localtime()) #和time.gmtime相反:接受一个时间元组形式,返回该时刻的时间辍 print calendar.weekday(2017, 6, 30) # calendar.weekday(year,month,day) return date code
def reservation_day(request): ts = Table.objects.all() if not ts: message = 'ERROR: A table map has not yet been set up.' return render_to_response('index.html', { 'message': message, }) months = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', ] calendar.setfirstweekday(calendar.SUNDAY) this_year = int(time.strftime('%Y', time.localtime())) next_year = this_year this_month = int(time.strftime('%m', time.localtime())) next_month = this_month + 1 if next_month == 13: next_year = next_year + 1 next_month = 1 this_month_cal = calendar.monthcalendar(this_year, this_month) next_month_cal = calendar.monthcalendar(next_year, next_month) this_month_year = '%s %d' % (months[this_month-1], this_year) next_month_year = '%s %d' % (months[next_month-1], next_year) message = 'Select the day when you would like to reserve a table.' return render_to_response('reservation_day.html', { 'message': message, 'this_month_cal': this_month_cal, 'next_month_cal': next_month_cal, 'this_month_year': this_month_year, 'next_month_year': next_month_year, })
def next_date(week, day_of_week): year, month = (now.year, now.month) day = calendar.monthcalendar(now.year, now.month)[week][day_of_week] if now.day > day: year = int(2014 + math.floor(11/12)) month = now.month % 12 + 1 day = calendar.monthcalendar(year, month)[week][day_of_week] return datetime(year, month, day, 18, 30)
def sol(n): a=calendar.monthcalendar(n,1)[0][-1] b=calendar.monthcalendar(n,3)[0][-1] for i in range(1,10000): p=calendar.monthcalendar(n+i,1)[0][-1] q=calendar.monthcalendar(n+i,3)[0][-1] if a==p and b==q: return i
def Ch_buts(self,arb,pmo,pdy,pyr): ''' Assign appropriate labels to button layout arb=array of button instances pmo,pdy,pyr = date to open with ''' arb[len(arb)-3].text=str(calendar.month_abbr[pmo]) arb[len(arb)-2].text=str(pdy) arb[len(arb)-1].text=str(pyr) dy=calendar.monthcalendar(pyr,pmo) tod=date.today().timetuple() tt=tod[2] if (tod[0]!= pyr) or (tod[1]!= pmo): tt=100 amo=pmo+1;ayr=pyr bmo=pmo-1;byr=pyr if (pmo==12): amo=1;ayr=pyr+1 if (pmo==1): bmo=12;byr=pyr-1 ay=calendar.monthcalendar(ayr,amo) by=calendar.monthcalendar(byr,bmo) for i in range(len(dy)): for j in range(0,7): arb[i*7+j].text=str(dy[i][j]) arb[i*7+j].background_color=(1,1,1,1) if dy[i][j]== pdy: arb[i*7+j].text='[color=ff0000][b]'+str(dy[i][j])+'[/b][/color]' if dy[i][j]== tt: #FIX TODAY STAMP arb[i*7+j].text='[color=ffff00][b]'+str(dy[i][j])+'[/b][/color]' for i in range(len(dy[0])): if dy[0][i]==0: dy[0][i]=by[len(by)-1][i] arb[i].text=str(dy[0][i]) arb[i].background_color=(.5,1,1,0) if len(dy)==5: if dy[len(dy)-1][6]== 0: dy.append(ay[1]) for j in range(0,7): arb[35+j].text=str(dy[5][j]) arb[35+j].background_color=(.5,1,1,0) for i in range(0,7): if dy[4][i]==0: dy[4][i]=ay[0][i] arb[28+i].text=str(dy[4][i]) arb[28+i].background_color=(.5,1,1,0) else: dy.append(ay[0]) for j in range(0,7): arb[35+j].text=str(dy[5][j]) arb[35+j].background_color=(.5,1,1,0) else: for i in range(len(dy[5])): if dy[5][i]==0: dy[5][i]=ay[0][i] arb[35+i].text=str(dy[5][i]) arb[35+i].background_color=(.5,1,1,0)
def getfutureexpiredate(nowdate=None): if not nowdate: nowdate = dt.date.today() if not nowdate.month % 3: c1 = calendar.monthcalendar(nowdate.year, nowdate.month) if nowdate.month == 12: c2 = calendar.monthcalendar(nowdate.year + 1, 3) nextyear = nowdate.year + 1 nextmonth = 3 else: c2 = calendar.monthcalendar(nowdate.year, (nowdate.month / 3 + 1) * 3) nextyear = nowdate.year nextmonth = (nowdate.month / 3 + 1) * 3 first_week1 = c1[0] second_week1 = c1[1] third_week1 = c1[2] first_week2 = c2[0] second_week2 = c2[1] third_week2 = c2[2] if first_week1[calendar.THURSDAY]: second_thursday1 = second_week1[calendar.THURSDAY] else: second_thursday1 = third_week1[calendar.THURSDAY] if first_week2[calendar.THURSDAY]: second_thursday2 = second_week2[calendar.THURSDAY] else: second_thursday2 = third_week2[calendar.THURSDAY] if nowdate.day <= second_thursday1: expire_date = dt.date(nowdate.year, nowdate.month, second_thursday1) else: expire_date = dt.date(nextyear, nextmonth, second_thursday2) return expire_date else: c2 = calendar.monthcalendar(nowdate.year, (nowdate.month / 3 + 1) * 3) nextyear = nowdate.year nextmonth = (nowdate.month / 3 + 1) * 3 first_week2 = c2[0] second_week2 = c2[1] third_week2 = c2[2] if first_week2[calendar.THURSDAY]: second_thursday2 = second_week2[calendar.THURSDAY] else: second_thursday2 = third_week2[calendar.THURSDAY] expire_date = dt.date(nextyear, nextmonth, second_thursday2) return expire_date
def most_frequent_days(year): fo328 = ["Monday","Sunday"] if year == 328: return fo328 week =["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] result = [] cal = calendar.monthcalendar(year, 1)[0] cal2 = calendar.monthcalendar(year, 12)[-1] for day in range(len(week)): if (cal[day] and cal2[day]) !=0: result.append(week[day]) return result
def test_structure_of_month(self): calendar.setfirstweekday(6) expectedAnswer = calendar.monthcalendar(2015, 11) monthCalender = self.calender.showMonth(2015, 11) self.assertEqual(expectedAnswer, monthCalender) expectedAnswer = calendar.monthcalendar(2015, 12) monthCalender = self.calender.showMonth(2015, 12) self.assertEqual(expectedAnswer, monthCalender) expectedAnswer = calendar.monthcalendar(2016, 1) monthCalender = self.calender.showMonth(2016, 1) self.assertEqual(expectedAnswer, monthCalender)
def getEventsForCalendar(self): year, month = self.year, self.month last_day = filter(lambda x: bool(x), calendar.monthcalendar(year, month)[-1])[-1] calendar.setfirstweekday(self.calendar.week['firstDay']-1) events = {} for event in getUtility(ICalendar).getEvents(year, month): end = event.endDate first = event.startDate.day if end.year > year or end.month > month: endDay = last_day else: endDay = end.day for day in range(first, endDay + 1): data = events.setdefault(day, []) data.append(event) todayDay = self.now[2] isToday = (self.now[1] == self.month) and (self.now[0] == self.year) data = [] for week in calendar.monthcalendar(year, month): data.append([]) weekdata = data[-1] for daynumber in week: if daynumber == 0: weekdata.append(0) continue day = {'day': daynumber} if isToday and (todayDay == daynumber): day['today'] = True else: day['today'] = False day['date'] = '%s-%s-%s' % (year, month, daynumber) if daynumber in events: for event in events[daynumber]: day['events'] = ' \n'.join( [event.title for event in events[daynumber]]) weekdata.append(day) return data
def calculate(): # Parameters: # Python meets happen on the last Monday of each month. # Leap Day happens every fourth year. # declare containers febList = [] fifthWeek = [] # other declarations controlBool = True myYear = 2016 # loop through time while (controlBool): myFebruary = calendar.monthcalendar(myYear, 2) febList = myFebruary listLength = len(febList) # specify the search if (listLength == 5): fifthWeek = febList[4] myMonday = fifthWeek[0] # test for a convergence if ((myYear > 2016) and (myMonday == 29)): break # increment year myYear += 1 print("\nThe next Leap Day Python Meet \nwill occur on February 29, " + str(myYear))
def calendarize(dt_one, dt_two=None, mark_today=False): """Renders a pretty calendar for a datetime's month. Because we access the attributes of the datetimes directly, we have to manually cast them into the timezone we want (otherwise we'd get utc days/times, which probably aren't correct for settings.TIMEZONE.) """ dt_one = dt_one.astimezone(pytz.timezone(settings.TIME_ZONE)) matrix = calendar.monthcalendar(dt_one.year, dt_one.month) if dt_two is None: dt_two = dt_one else: dt_two = dt_two.astimezone(pytz.timezone(settings.TIME_ZONE)) #print "Marking today: ", mark_today if mark_today: today = datetime.datetime.now(pytz.utc).astimezone(pytz.timezone(settings.TIME_ZONE)) else: today = None return { 'start': dt_one, 'end': dt_two, 'matrix': matrix, 'today': today, }
def genCalendar(date=mx.DateTime.now(), category=None, thispage=None, nohighlight=0): daylinks = [''] * 32 for day in range(1, date.days_in_month+1): if len(tv.weblog.db.getItemsAtDay(mx.DateTime.DateTime(date.year, date.month, day), category)) > 0: daylinks[day] = getRelativePath(getDayPageUrl(mx.DateTime.DateTime(date.year, date.month, day)), filenameToUrl(thispage)) else: daylinks[day] = '' previousmonth = tv.weblog.db.getPreviousMonthWithItems(date) nextmonth = tv.weblog.db.getNextMonthWithItems(date) calendarTemplate = templates.calendar.calendar(searchList=[ {'weeklist': calendar.monthcalendar(date.year, date.month), 'daynames': calendar.weekheader(2).split(' '), 'date': dateNamespace(date), 'daylinks': daylinks, 'nohighlight': nohighlight, 'monthpageurl': getRelativePath(getMonthPageUrl(date, category), filenameToUrl(thispage)), 'previousmonthurl': getRelativePath(getMonthPageUrl(previousmonth), filenameToUrl(thispage)), 'previousmonth': previousmonth, 'nextmonthurl': getRelativePath(getMonthPageUrl(nextmonth), filenameToUrl(thispage)), 'nextmonth': nextmonth, 'thisday': date.day }]) return str(calendarTemplate)
def calendar(request): from datetime import date import calendar today = date.today() weeks = calendar.monthcalendar(today.year, today.month) calendar_of_events = [] for week in weeks: week_events = [] for day in week: day_events = { 'day': 0, 'today': False, 'events': [], } day_events['day'] = day if day == today.day: day_events['today'] = True if day == 15: day_events['events'].append({'title': u'Название события1', 'desc': u'Описание'}) day_events['events'].append({'title': u'Название события2', 'desc': u'Описание'}) week_events.append(day_events) calendar_of_events.append(week_events) return render(request, 'events/events_calendar.html', { 'calendar': calendar_of_events } )
def month_cal(request, project_name, year, month): """Shows a large calendar with details for a month. Actions available: None """ project = get_project(request, project_name) access = get_access(project, request.user) year = int(year) month = int(month) interesting_months = project.get_interesting_months() month_data = [] for month_ in interesting_months: if month_[0]: month_datum = {} month_datum['name'] = datetime.date(month_[0], month_[1], month_[2]).strftime('%B %y') month_datum['href'] = '/%s/calendar/%s/%s/' % (project.shortname, month_[0], month_[1]) month_data.append(month_datum) starting_tasks = Task.objects.filter(project = project, expected_start_date__year = year, expected_start_date__month = month) ending_tasks = Task.objects.filter(project = project, expected_end_date__year = year, expected_end_date__month = month) month_dates = cal.monthcalendar(year, month) flattened_dates = flatten(month_dates) start_dates_array = [[] for i in range(len(flattened_dates))] for task in starting_tasks: index = flattened_dates.index(task.expected_start_date.day) start_dates_array[index].append(task) end_dates_array = [[] for i in range(len(flattened_dates))] for task in ending_tasks: index = flattened_dates.index(task.expected_end_date.day) end_dates_array[index].append(task) d = zip(flattened_dates, start_dates_array, end_dates_array) month_dates = unflatten(d) weekheader = cal.day_name payload = locals() return render(request, 'project/calendar.html', payload,)
def show_days(self): """ display days in HTML format as table rows""" list_day_events = self.get_days_events() days = [] for week in calendar.monthcalendar(self.getYear(), self.getMonth()): days.append('<tr>\n ') day_number = 0 for day in week: l_headers = self.get_weekheader(9)[day_number][0] curr_date = "%s/%s/%s" % (str(self.getYear()), string.zfill(str(self.getMonth()),2), string.zfill(str(day),2)) if day == 0: days.append('<td>') elif DateTime(curr_date).isCurrentDay(): days.append('<td class="today">') else: days.append('<td>') if day==0: days.append(' </td>\n') day_number += 1 continue if curr_date in list_day_events: days.append('<a href="%s/show_day_events?date=%s">%s</a></td>' % (self.absolute_url(), curr_date, str(day))) else: days.append('%s</td>' % str(day)) day_number += 1 days.append('</tr>\n') return ''.join(days)
def _compute_weeks_for_months(self, current_year): weeks_in_months = [] weekCounter = 0 for month_index in self.MONTHS: monthcalendar = calendar.monthcalendar(current_year, month_index) days_in_week = [len([1 for day in weeks if day]) for weeks in monthcalendar] # if a weekly chuck has more than 4 days we'll keep it and count it as a full week weeks_in_current_month = sum(1 for daycount in days_in_week if daycount > 3) # since the assumption of 4 days is somewhat random, let's doublecheck # the number of weeks weekCounter = weekCounter + weeks_in_current_month if (weekCounter > 52): weeks_in_months.append(52 - (weekCounter - weeks_in_current_month)) else: weeks_in_months.append(weeks_in_current_month) weekIndex = 1 week_indexes_for_months = [] for index in self.MONTHS: week_indexes_for_months.append([]) for _ in range(weeks_in_months[index-1]): # add each week into the monthly raster week_indexes_for_months[index-1].append(weekIndex) weekIndex += 1 return week_indexes_for_months
def get_no_of_days(self): no_of_days_in_month = calendar.monthrange(getdate(nowdate()).year, getdate(nowdate()).month) no_of_holidays_in_month = len([1 for i in calendar.monthcalendar(getdate(nowdate()).year, getdate(nowdate()).month) if i[6] != 0]) return [no_of_days_in_month[1], no_of_holidays_in_month]
def fnFillCalendar(self): init_x_pos = 20 arr_y_pos = [110,130,150,170,190,210] intposarr = 0 self.canvas.delete("DayButton") self.canvas.update() intyear = int(self.year_var.get()) monthcal = calendar.monthcalendar(intyear, self.intmonth) for row in monthcal: xpos = init_x_pos ypos = arr_y_pos[intposarr] for item in row: stritem = str(item) if stritem == "0": xpos += 27 else : tagNumber = tuple((self.tagBaseNumber,stritem)) self.canvas.create_text(xpos, ypos , text=stritem, font=fnta,tags=tagNumber) xpos += 27 intposarr += 1 #self.canvas.tag_bind ("DayButton", "<ButtonRelease-1>", self.fnClickNumber) self.canvas.tag_bind ("DayButton", "<Double-ButtonPress-1>", self.fnClickNumber) self.canvas.tag_bind ("DayButton", "<Enter>", self.fnOnMouseOver) self.canvas.tag_bind ("DayButton", "<Leave>", self.fnOnMouseOut)
def getEventsForCalendar(self, month='1', year='2002'): """ recreates a sequence of weeks, by days each day is a mapping. {'day': #, 'url': None} """ year=int(year) month=int(month) # daysByWeek is a list of days inside a list of weeks, like so: # [[0, 1, 2, 3, 4, 5, 6], # [7, 8, 9, 10, 11, 12, 13], # [14, 15, 16, 17, 18, 19, 20], # [21, 22, 23, 24, 25, 26, 27], # [28, 29, 30, 31, 0, 0, 0]] daysByWeek=calendar.monthcalendar(year, month) weeks=[] events=self.catalog_getevents(year, month) for week in daysByWeek: days=[] for day in week: if events.has_key(day): days.append(events[day]) else: days.append({'day': day, 'event': 0, 'eventslist':[]}) weeks.append(days) return weeks
def gridMonth(self, stuff): year, month = self.monthYear.get() self.year = year self.month = month row = 1 col = 0 cal = calendar.monthcalendar(year, month) for dname in "MTWTFSS": l=Label(self, text=dname, width=2) l.grid(row=row, column=col) col=col+1 row = 2 col = 0 for w in cal: for d in w: if d: b=Button(self, text=d, width=2, command=lambda self=self, day=d: self.returnDay(day)) b.grid(row=row, column=col) if col>4: b.config() if d==self.day and self.year==self.thisYear and self.month==self.thisMonth: b.config() col=col+1 row=row+1 col=0
def find_day_by_weekday_offset(year, month, weekday, offset): # get the id of the weekday (1 for Tuesday) weekday_id = Daterange.get_weekday_id(weekday) if weekday_id is None: return None # same for month month_id = Daterange.get_month_id(month) if month_id is None: return None # thanks calendar :) cal = calendar.monthcalendar(year, month_id) # If we ask for a -1 day, just reverse cal if offset < 0: offset = abs(offset) cal.reverse() # ok go for it nb_found = 0 try: for i in xrange(0, offset + 1): # in cal 0 mean "there are no day here :)" if cal[i][weekday_id] != 0: nb_found += 1 if nb_found == offset: return cal[i][weekday_id] return None except Exception: return None
def _last_of_month(self, day_of_week=None): """ Modify to the last occurrence of a given day of the week in the current month. If no day_of_week is provided, modify to the last day of the month. Use the supplied consts to indicate the desired day_of_week, ex. DateTime.MONDAY. :type day_of_week: int or None :rtype: DateTime """ dt = self.start_of("day") if day_of_week is None: return dt.set(day=self.days_in_month) month = calendar.monthcalendar(dt.year, dt.month) calendar_day = (day_of_week - 1) % 7 if month[-1][calendar_day] > 0: day_of_month = month[-1][calendar_day] else: day_of_month = month[-2][calendar_day] return dt.set(day=day_of_month)
def month_calendar(year, month, days, service): calendar.setfirstweekday(calendar.SUNDAY) month_calendar = calendar.monthcalendar(int(year), int(month)) month_name = calendar.month_name[int(month)] month_href = reverse('services:month', args=(service.slug, year, month)) html = '<table><thead>' html += '<tr><th colspan="7"><a href="{0}">{1}</a></th></tr>'.format(month_href, month_name) html += '<tr><th>s</th><th>m</th><th>t</th><th>w</th><th>t</th><th>f</th><th>s</th></tr>' html += '</thead><tbody>' for week in month_calendar: html += '<tr>' for day in week: if day == 0: str_day = '' else: str_day = str(day).zfill(2) if str_day in days: day_href = reverse('services:day', args=(service.slug, year, month, str_day)) html += '<td><a href="{0}">{1}</a></td>'.format(day_href, str_day) else: html += '<td>{0}</td>'.format(str_day) html += '</tr>' html += '</tbody></table>' return html
def _first_of_month(self, day_of_week): """ Modify to the first occurrence of a given day of the week in the current month. If no day_of_week is provided, modify to the first day of the month. Use the supplied consts to indicate the desired day_of_week, ex. pendulum.MONDAY. :type day_of_week: int :rtype: Date """ dt = self if day_of_week is None: return dt.set(day=1) month = calendar.monthcalendar(dt.year, dt.month) calendar_day = (day_of_week - 1) % 7 if month[0][calendar_day] > 0: day_of_month = month[0][calendar_day] else: day_of_month = month[1][calendar_day] return dt.set(day=day_of_month)
def getEntryForCalendar(self, month, year): # # Returns entries on month, # For every days in calendar,if entry exists, # store data for mapping following... # {'day': #, 'entry': None} # year=int(year) month=int(month) daysByWeek=calendar.monthcalendar(year, month) weeks=[] enteirs_in_month=self.getEntryInDate(year,month,full_objects=False) entries = {} for entry in enteirs_in_month: day = DateTime(entry.Date).day() entries[day] = 1 for week in daysByWeek: days=[] for day in week: if entries.has_key(day): days.append({'day':day,'entry':1}) else: days.append({'day':day,'entry':None}) weeks.append(days) return weeks
def index(request, project_name): """The calendars index page. Shows calendars for intersting months. (Months in which a task stars or ends.) Actions available: None""" project = get_project(request, project_name) access = get_access(project, request.user) interesting_months = project.get_interesting_months() month_data = [] for month in interesting_months: if month[0]: month_datum = {} month_datum['name'] = datetime.date(month[0], month[1], month[2]).strftime('%B %y') month_datum['href'] = '/%s/calendar/%s/%s/' % (project.shortname, month[0], month[1]) month_cal = cal.monthcalendar(month[0], month[1]) flattened_dates = flatten(month_cal) start_tasks = project.task_start_dates_month(month[0], month[1]) end_tasks = project.task_end_dates_month(month[0], month[1]) start_dates_array = [[] for i in range(len(flattened_dates))] end_dates_array = [[] for i in range(len(flattened_dates))] for task in start_tasks: index = flattened_dates.index(task[0].day) start_dates_array[index].append(task[1]) for task in end_tasks: index = flattened_dates.index(task[0].day) end_dates_array[index].append(task[1]) d = zip(flattened_dates, start_dates_array, end_dates_array) month_datum['calendar'] = unflatten(d) month_data.append(month_datum) weekheader = cal.day_abbr payload = locals() return render(request, 'project/calendarindex.html', payload,)
def getMonthMatrix(year, month): """Return matrix of dates in the month in the 7x6 format.""" matrix = calendar.monthcalendar(year, month) blank_week = [0,0,0,0,0,0,0] last_month = goMonth(datetime.date(year, month, 1), -1) next_month = goMonth(datetime.date(year, month, 1), 1) last_month_day = calendar.monthrange(last_month.year, last_month.month)[1] next_month_day = 1 first_week = matrix[0] for idx in range(6, -1, -1): if first_week[idx] == 0: first_week[idx] = datetime.date(last_month.year, last_month.month, last_month_day) last_month_day -= 1 for week_idx in range(0, 6): try: week = matrix[week_idx] except IndexError: week = list(blank_week) matrix.append(week) for day_idx, day in enumerate(week): if isinstance(day, datetime.date): continue if day == 0: week[day_idx] = datetime.date(next_month.year, next_month.month, next_month_day) next_month_day += 1 continue # current month and year week[day_idx] = datetime.date(year, month, day) return matrix
def __init__(self, year=None, month=None): """ Creates calendar @param year: Calendar year @type year: int @param month: Calendar month @type month: int @return: list """ w = 0 cal = [] if year is None or month is None: today = datetime.datetime.now() year = today.year month = today.month weeks = calendar.monthcalendar(year, month) for week in weeks: self.append([]) for day in week: if day > 0: day = datetime.datetime(year, month, day).date() self[w].append(day) else: self[w].append(None) w += 1
def agenda(year=None, month=None, day=None): summary_agenda_form = get_summary_agenda_form() if year is None and month is None and day is None: day_to_emph = datetime.date.today() else: try: if month == 13: year = year + 1 month = 1 elif month == 0: year = year - 1 month = 12 else: day_to_emph = datetime.date.today() day_to_emph = datetime.date(year, month, day) except ValueError: day_to_emph = (datetime.date(year, month + 1, 1) - datetime.timedelta(1)) summary_agenda_form.day.data = day_to_emph cal = calendar.monthcalendar(day_to_emph.year, day_to_emph.month) return render_template('monthly_agenda.html', summary_agenda_form=summary_agenda_form, day_to_emph=day_to_emph, datetime=datetime, calendar=calendar, cal=cal)
def get_month_list(self): '''Get the current month calendar as a list of dates''' month = calendar.monthcalendar(self.year, self.month) return [day for week in month for day in week]
# zeroes mean that the day of the week is in an overlapping month for i in c.itermonthdays(2020, 1): print(i) # The Calendar module provides useful utilities for the given locale, # such as the names of days and months in both full and abbreviated forms for name in calendar.month_name: print(name) for name in calendar.day_name: print(name) # Calculate days based on a rule: For example, consider # a team meeting on the first Friday of every month. # To figure out what days that would be for each month, # we can use this script: print("Team meatings will be on:") for m in range(1, 13): cal = calendar.monthcalendar(2020, m) week1 = cal[0] week2 = cal[1] if week1[calendar.FRIDAY] != 0: meetday = week1[calendar.FRIDAY] else: meetday = week2[calendar.FRIDAY] print("%10s %2d" % (calendar.month_name[m], meetday))
def main(): today = datetime.datetime.date(datetime.datetime.now()) current = re.split('-', str(today)) current_no = int(current[1]) current_month = year[current_no - 1] current_day = int(re.sub('\A0', '', current[2])) current_yr = int(current[0]) print ''' content-type: text/html\n\n <html> <head> <meta charset="utf-8"> <link href='http://fonts.googleapis.com/css?family=PT+Sans:400,700,400italic,700italic' rel='stylesheet' type='text/css'> <link href='http://fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700' rel='stylesheet' type='text/css'> <style> body { line-height: 1; margin: 50px; } div { background: rgba(0, 0, 0, .1); border-radius: 5px; box-sizing: border-box; padding: 15px; width: 220px; } header { overflow: clear; position: relative; } h2 { font-family: 'PT Sans Narrow', sans-serif; font-size: 18px; font-weight: 700; margin: 0 0 10px; text-align: center; } button { position: absolute; top: -4px; } button:first-child { left: 0; } button:last-child { right: 0; } table { background: #fff; border-collapse: collapse; color: #222; font-family: 'PT Sans', sans-serif; font-size: 13px; width: 100%; } td { border: 1px solid #ccc; color: #444; line-height: 22px; text-align: center; } tr:first-child td { color: #222; font-weight: 700; } .selected { background: #f0951d; border: 0; box-shadow: 0 2px 6px rgba(0, 0, 0, .5) inset; } </style> </head> <body> <div> <header> <button><<</button> <h2>July 2013</h2> <button>>></button> </header> <table> <tr> <td>S</td> <td>M</td> <td>T</td> <td>W</td> <td>Th</td> <td>F</td> <td>S</td> </tr> <tr> <td></td> <td></td> <td>1</td> <td>2</td> <td>3</td> <td>4</td> <td>5</td> </tr> <tr> <td>6</td> <td>7</td> <td>8</td> <td>9</td> <td>10</td> <td>11</td> <td>12</td> </tr> <tr> <td>13</td> <td>14</td> <td>15</td> <td>16</td> <td class="selected">17</td> <td>18</td> <td>19</td> </tr> <tr> <td>20</td> <td>21</td> <td>22</td> <td>23</td> <td>24</td> <td>25</td> <td>26</td> </tr> <tr> <td>27</td> <td>28</td> <td>29</td> <td>30</td> <td>31</td> <td></td> <td></td> </tr> </table> </div> </body> </html> ''' print '%s %s' % (current_month, current_yr) print ''' ''' month = calendar.monthcalendar(current_yr, current_no) nweeks = len(month) for w in range(0, nweeks): week = month[w] print "" for x in xrange(0, 7): day = week[x] if x == 5 or x == 6: classtype = 'weekend' else: classtype = 'day' if day == 0: classtype = 'previous' print '' % (classtype) elif day == current_day: print '%s, %d, %s' % (classtype, day, classtype) else: print '%s, %d, %s' % (classtype, day, classtype) print "" print ''' '''
fileEmpty = os.stat(path_file).st_size == 0 if fileEmpty: with open(path_file, "a+") as csvfile: writer = csv.writer(csvfile) writer.writerow(header_file) with open(path_file, mode='a', newline='') as csvfile: writer = csv.writer(csvfile) writer.writerows(list_info) #Criar todas as datas para o mês de janeiro. year = 2020 month = 3 JanMonth = calendar.monthcalendar(2020, 3) #loop over the month for i in range(len(JanMonth)): for j in range(len(JanMonth[0])): if JanMonth[i][j] != 0: dateIs = JanMonth[i][j] dayWeek = datetime.datetime(year, month, dateIs) dayOfWeek = dayWeek.weekday() #Create String to get the html if dayOfWeek < 5: firstPartStr = "http://bvmf.bmfbovespa.com.br/market-data/html/md_stats_" + str( year) + str(month).rjust(2, '0') + str(dateIs).rjust( 2, '0') + ".html"
def __get_week_count__(self): return len(callib.monthcalendar(self.year, self.month))