def _get_month_nth_weekday(self, in_date): """ Returns ZERO based nth date in month which weekday is the same as given (First monday, first sunday, second sunday etc...) @param in_date (date): random date in month @param weekday (int) : weekday index (0 --> Monday, ..., 6 --> Sunday) @param nth (int) : number of weekday match (-1 --> Last, 0 --> First,...) """ cal = Calendar(firstweekday=0) weekday = self._get_choosen_weekday() nth = self._get_choosen_weekday_position() month = in_date.month datelist = cal.itermonthdates(in_date.year, month) msg = 'nth ({}) param can not be less than -1 in _get_month_nth_weekday' assert nth >= -1, msg.format(nth) valid = [ item for item in datelist \ if item.weekday() == weekday and item.month == month ] return valid[nth] if len(valid) >= nth else None
def generate_random(): 'Generates a years worth of random logs.' p = path('c:\\test') words = 'foo bar to be or not the and apple orange banana cherry futon proleptic gregorian ordinal'.split() cal = Calendar() for month in xrange(1, 12): for day in cal.itermonthdates(2007, month): messages = [] for x in xrange(2, randrange(20, 50)): shuffle(words) messages.append( S(buddy = S(name = 'digsby0%d' % randrange(1, 3)), timestamp = random_time_in_day(day), message = ' '.join(words[:randrange(1, len(words)+1)]))) messages.sort(key = lambda mobj: mobj['timestamp']) daylog = p / (day.isoformat() + '.html') with daylog.open('w') as f: f.write(html_header % dict(title = 'IM Logs with %s on %s' % ('digsby0%d' % randrange(1, 3), day.isoformat()))) for mobj in messages: f.write(generate_output_html(mobj))
def _dates_in_month(year, month): """ Returns a list of date objects for each date in the month """ calendar = Calendar() dates = calendar.itermonthdates(year, month) return [date for date in dates if date.month == month]
def meetup_day(year, month, day_of_week, classifier): c_idx = { 'first': 0, '1st': 0, '2nd': 1, '3rd': 2, '4th': 3, '5th': 4, 'last': -1 } cal = Calendar() # only get the days of the month which correspond to day_of_week # itermonthdates returns full weeks either side, so we filter on the month candidates = [ dt.day for dt in cal.itermonthdates(year, month) if day_name[dt.weekday()] == day_of_week and dt.month == month ] date_fn = partial(date, year, month) if classifier.endswith('teenth'): return date_fn(next(d for d in candidates if 13 <= d <= 19)) elif c_idx[classifier] < len(candidates): return date_fn(candidates[c_idx[classifier]]) raise Exception('meetup day not found!')
def checks_to_calendar_days(checks): ## Generate input data for calendar # TODO: This needs to be done MUCH better now = datetime.strptime(checks[0]['when'], '%Y-%m-%d') cal = Calendar(0) pick_checks = False i = -1 days = [] for day in cal.itermonthdates(now.year, now.month): if now.date() + timedelta(6) >= day >= now.date(): pick_checks = True i += 1 days.append({ 'day_number': day.day, 'when': [ day.strftime('%Y-%m-%d') + '-AM', day.strftime('%Y-%m-%d') + '-PM' ], 'outside': True if day.month != now.month else False, 'code': checks[i]['code'] if pick_checks else None, 'reasons': checks[i]['reasons'] if pick_checks else None, 'blocked': False if pick_checks else True }) pick_checks = False title = ' '.join([now.strftime("%B"), str(now.year)]) return days, title
def get_date_table(): year = datetime.now().year month = datetime.now().month day = datetime.now().day c = Calendar(firstweekday=0) table = [ eval(x.strftime("{'year':%Y,'month':%-m,'day':%-d}")) for x in c.itermonthdates(year, month) ] class_table = get_up_date(year, month) for x in table: if x in class_table: x['up'] = True else: x['up'] = False if x['month'] == month: x['show'] = True if x['day'] == day: x['today'] = True else: x['today'] = False else: x['show'] = False return table, year, datetime.now().strftime("%b")
def sick(request,user_id): users = User.objects.all() selected = User.objects.get(pk=user_id) user_days = Day.objects.filter_user(user_id) year_form = YearChangeForm({'year':request.session.get('year',2013)}) year = int(request.session.get('year',2013)) cal = MikranCalendar(user_days,year) if request.method == 'POST': # If the form has been submitted... form = SickForm(user=request.user, data=dict(request.POST.items() + {'user_id':selected.id}.items())) # A form bound to the POST data if form.is_valid(): # All validation rules pass start_date = datetime.date(int(request.POST['first_day_year']), int(request.POST['first_day_month']), int(request.POST['first_day_day'])) end_date = datetime.date(int(request.POST['last_day_year']), int(request.POST['last_day_month']), int(request.POST['last_day_day'])) start_month = int(request.POST['first_day_month']) end_month = int(request.POST['last_day_month']) status_obj = Status.objects.get(status=form.translateChoice(request.POST['status'])); days = [] current = Calendar() for month in range(start_month,end_month+1): for day in current.itermonthdates(int(request.POST['first_day_year']),month): if day >= start_date and day <= end_date: if day.isoweekday() < 6: if not day in days: if not day.strftime("%02d-%02m-%04Y") in cal.get_free_days(year): days.append(day) #build list of objects for bulk create Day.objects.bulk_create([Day(user_id=selected.id,status_id=status_obj.id,leave_date=day) for day in days]) #send bulk sick days create signal days_planned.send(sender=User, user=selected, status=status_obj, start=start_date, end=end_date, operation="SICK".encode('utf-8')) #display OK message for the user messages.add_message(request,messages.INFO, 'Zgłosiłeś zwolnienie lekarskie od %s do %s' %(start_date,end_date)) return HttpResponseRedirect(reverse('leave.views.show_user',args=(selected.id,))) else: form = SickForm() return render_to_response('sick_days.html',{'users': users, 'selected':selected, 'user_days':user_days, 'cal':mark_safe(cal.formatyear(year,4)), 'year_form':year_form, 'days_present': user_days.filter_present().count(), 'days_sick':user_days.filter_sick().count(), 'days_planned':user_days.filter_planned().count(), 'days_accepted':user_days.filter_accepted().count(), 'form':form}, context_instance=RequestContext(request))
def make_flights_by_weekday(city_from, city_to, days, time): calendar = Calendar() for i in range(3): for day in calendar.itermonthdates(this_year, this_month + i): if day.month == this_month + i and day.weekday() in days: date_str = day.strftime('%d-%m-%Y') FLIGHTS[city_from][city_to].append( [date_str, WEEKDAYS[day.weekday()], time])
def prepare_month_dates(year, month): calendar = Calendar() dates = calendar.itermonthdates(year, month) month_dates = [] for date in dates: if date.month == month: month_dates.append(date) return month_dates
def meetup_day(year, month, weekday_name, which): cal = Calendar() weekday = WEEKDAYS.index(weekday_name) days = [d for d in cal.itermonthdates(year, month) if d.month == month and d.weekday() == weekday] if (which == "teenth"): return find_teenth(days) else: return days[WEEK_ORD[which]]
def get_all_calendar_dates(year: int, planner_start_day: DayOfTheWeek) -> List[date]: calendar_dates = [] calendar = Calendar() calendar.setfirstweekday(planner_start_day.value) for month in range(1, 13): for full_date in calendar.itermonthdates(year=year, month=month): calendar_dates.append(full_date) return calendar_dates
def display(self): calendar = Calendar(0) dates_iterator = calendar.itermonthdates(self.year, self.month) sys.stdout.write('\n') for i, day_date in enumerate(dates_iterator): if day_date.month != self.month: sys.stdout.write('\t') continue DayList(day_date, i).display() sys.stdout.write('\n')
def get_context_data(self, **kwargs): def get_weekday_text(athlete, weekday): morph = pymorphy2.MorphAnalyzer() if athlete.week_day: for week_day in eval(athlete.week_day): if weekday < int(week_day): day_text = morph.parse(Athlete.WEEK_DAYS[int(week_day)][1])[0].inflect({'accs'}).word return 'во' if Athlete.WEEK_DAYS[int(week_day)][0] == 1 else 'в', day_text day_text = morph.parse(Athlete.WEEK_DAYS[int(eval(athlete.week_day)[0])][1])[0].inflect({'accs'}).word return 'во' if Athlete.WEEK_DAYS[int(eval(athlete.week_day)[0])][0] == 1 else 'в', day_text return 'не', 'запланирована' athlete = Athlete.objects.get_or_create(user=self.request.user)[0] today = datetime.now().date() cal = Calendar(MONDAY) year = int(self.kwargs.get('year')) month = int(self.kwargs.get('month')) day = int(self.kwargs.get('day')) current_date = date(year, month, day) next_month = add_months(current_date, 1) prev_month = sub_months(current_date, 1) month_dates = list(cal.itermonthdates(year, month)) trainings = Training.objects.filter( date__in=month_dates, workout_diary=self.object ) month_dates_with_training = [ (item, True) if athlete.week_day and item >= today and str(item.weekday()) in athlete.week_day else (item, trainings.filter(date=item).last()) for item in month_dates ] splited = chunks(month_dates_with_training, 7) month = [(week[0][0].isocalendar()[1] == today.isocalendar()[1], week) for week in splited] training_today = athlete.week_day and (str(today.weekday()) in athlete.week_day) training = get_training(self.request.user, current_date) ctx = { 'training': training, 'today': today, 'month': month, 'prev_month': prev_month, 'next_month': next_month, 'current_month': month_text(current_date.month), 'current_date': current_date, 'current_weekday': Athlete.WEEK_DAYS[current_date.weekday()][1], 'training_duration': athlete.get_training_duration_display(), 'history': current_date < today, 'training_today': training_today, 'button_text': (True, 'Начать тренировку') if training_today else (False, 'Следующая тренировка %s %s' % get_weekday_text(athlete=athlete, weekday=today.weekday())) } return ctx
def __init__(self, start_date: date, days: int, max_events_visited: int): self.start_date = start_date self.expire_date = self.start_date + timedelta(days=days) self.events_visited = [] self.max_events_visited = max_events_visited c = Calendar() start_month = list( c.itermonthdates(self.start_date.year, self.start_date.month)) self._start_month_days = list( filter(lambda d: d >= self.start_date, start_month)) expire_month = c.itermonthdates(self.expire_date.year, self.expire_date.month) self._expire_month_days = list( filter(lambda d: d <= self.expire_date, expire_month)) self._days = self._start_month_days + self._expire_month_days
def makeDaysSetOfMonth(): today = datetime.datetime.now() cl = Calendar(firstweekday=0) list1 = list(cl.itermonthdates(today.year, today.month)) for elem in reversed(list1): if not elem.month == today.month: list1.remove(elem) list2 = [] for _, elem in enumerate(list1): list2.append(str(elem.weekday())) return list2
def thursdays(): from calendar import Calendar c = Calendar() days = [] thursday = 3 for i in range(1, 13): for d in c.itermonthdates(2018, i): if d.weekday() == thursday: days.append(d) with open('thursdays.txt', 'w') as f: for day in days: f.write(day.strftime('%d-%m-%Y\n'))
def __init__(self, now: date): self.id = now.month self.loc_key = Loc.MONTHS[self.id - 1] self.year = now.year c = Calendar() self.days = list( map(lambda d: DayData(d), c.itermonthdates(now.year, now.month))) self.today = next(d for d in self.days if d.date == now) self.events = []
def meetup_day(year, month, name, desc): cal = Calendar() weekday = WEEKDAY[name] days = [day for day in cal.itermonthdates(year, month) if day.month == month and day.weekday() == weekday] if desc[0].isdigit(): digit = int(desc[0]) return days[digit - 1] elif desc == "last": return days[-1] elif desc == "teenth": return find_if(days, lambda x: x.day in TEENTH)
def calendar_iter(self): calendar = Calendar() events = self.get_queryset() today = date.today() for i, d in enumerate(calendar.itermonthdates(self.year, self.month)): classes = [] if i % 7 == 0: week_n = d.isocalendar()[1] week = [] if d == today: classes.append('today') week.append((d, events.filter(date__day=d.day), classes)) if i % 7 == 6: yield week_n, week
def meetup_day(year, month, weekday, specifier): cal = Calendar() selectors = { '1st': lambda days: days[0], '2nd': lambda days: days[1], '3rd': lambda days: days[2], '4th': lambda days: days[3], 'last': lambda days: days[-1], 'teenth': lambda days: next((day for day in days if day.day > 9)) } preselected_days = filter( lambda day: day.strftime('%A') == weekday and day.month == month, cal.itermonthdates(year, month)) return selectors[specifier](preselected_days)
def _days_table(self, year, month): calendar = Calendar() table = '' for idx, day in enumerate(calendar.itermonthdates(year, month)): if day.month == month: if day == self.distinguished_day: string = self.distinguish_prefix + '{:>2}'.format( str(day.day)) + self.distinguish_suffix else: string = str(day.day) else: string = '' table += '{:>2} '.format(string) if idx % 7 == 6: table += '\n' return table.strip("\n")
def makeDateSetOfMonth(): today = datetime.datetime.now() cl = Calendar(firstweekday=0) list1 = list(cl.itermonthdates(today.year, today.month)) list2 = [] for elem in reversed(list1): if not elem.month == today.month: list1.remove(elem) days = ["(月)", "(火)", "(水)", "(木)", "(金)", "(土)", "(日)"] for elem in list1: list2.append( str(elem.month) + "月" + str(elem.day) + "日" + days[elem.weekday()]) # print(list2) return list2
def createMonths(yr, birth, feier, bild): cal = Calendar(0) x, y = 0, 0 drawString = "\\begin{figure}[!h]\n\\centering\n" if bild != "none": drawString += "\\tikz[overlay,remember picture]\\node[opacity=0.4]at (current page.center) {\includegraphics{" + bild + "}};" drawString += "\\begin{tikzpicture}[y=0.80pt, x=0.8pt,yscale=-1, inner sep=0pt,outer sep=0pt]" drawString += createYear(yr) for i in range(1, 13): x = x + 300 y = 0 drawString += "\n" + createRectangle(x, y, 0, i, dict(), dict(), 1) for ii in cal.itermonthdates(yr, i): drawString += "\n" + createRectangle(x, y, ii, i, birth, feier) drawString += "\end{tikzpicture}\n \n \end{figure}" return drawString
def makeDateSetOfMonth(timeDate): #datetimeオブジェを引数としてうけとって生成します。 OpeDay = timeDate cl = Calendar(firstweekday=0) list1 = list(cl.itermonthdates(OpeDay.year, OpeDay.month)) list2 = [] for elem in reversed(list1): if not elem.month == OpeDay.month: list1.remove(elem) days = ["(月)", "(火)", "(水)", "(木)", "(金)", "(土)", "(日)"] for elem in list1: list2.append( str(elem.month) + "月" + str(elem.day) + "日" + days[elem.weekday()]) # print(list2) return list2
def reminders_calendar(request, year=datetime.now().year, month=datetime.now().month): """Show a calendar of all reminders for a user""" month = int(month) year = int(year) months = get_months() today = datetime.now().date() # Set a set of year between now and 20 years in the future years = [x for x in range(datetime.now().year, datetime.now().year + 20)] # Get the selected month m = months[str(month)] # Create a calendar starting with Sunday from the last month cal = Calendar(SUNDAY) # Get all the days in the calendar month and year specified days = [day for day in cal.itermonthdates(year, month)] # Group the days into weeks going from Sunday to Saturday weeks = [days[i * 7:(i + 1) * 7] for i in range((len(days) / 7 + 1))] # Find the next and previous months next_month, previous_month = get_next_and_previous(year, month) # Get all of the reminders that happen in the current month reminders = Reminder.objects.filter(user=request.user, sent=False) reminder_dates = [reminder.date.date() for reminder in reminders if reminder.date.date().month == month] if request.method == 'POST': selected_month = request.POST.get('month') selected_year = request.POST.get('year') return redirect('calendar-date', year=selected_year, month=selected_month) context = { 'weeks': weeks, 'months': months, 'today': today, 'm': m, 'year': year, 'years': years, 'next_month': next_month, 'previous_month': previous_month, 'reminders': reminders, 'reminder_dates': reminder_dates, } return render(request, 'reminders/calendar.html', context)
def list_book_for_month(year, month): """List all days for given month, and for each day list fact book entry. """ data = asyncio.run(fetch_month_data(year, month)) cal = Calendar() print("%12s | %12s | %12s | %12s" % ("day", "shares", "trades", "dollars")) print("%12s-+-%12s-+-%12s-+-%12s" % ("-" * 12, "-" * 12, "-" * 12, "-" * 12)) for day in cal.itermonthdates(year, month): if day.month != month: continue if day in data: shares, trades, dollars = data[day] else: shares, trades, dollars = 0, 0, 0 print("%12s | %12s | %12s | %12s" % (day, shares, trades, dollars))
def makeDaysSetOfMonth(timeDate): OpeDay = timeDate cl = Calendar(firstweekday=0) list1 = list(cl.itermonthdates(OpeDay.year, OpeDay.month)) for elem in reversed(list1): if not elem.month == OpeDay.month: list1.remove(elem) list2 = [] for _, elem in enumerate(list1): if jpholiday.is_holiday(elem) or elem.weekday() >= 5: list2.append(1) else: list2.append(0) #休みの日なら1、そうでなければ0が入る # print(list2) return list2
def meetup_day(year, month, day_of_week, suffix): cal = Calendar(1) dayList = list(cal.itermonthdates(year, month)) # Translate human numbers to real numbers dateDic = { '1st': 0, '2nd': 1, '3rd': 2, '4th': 3, 'last': -1, } # Translate human days to numeric days dayDic = { 'Monday': 0, 'Tuesday': 1, 'Wednesday': 2, 'Thursday': 3, 'Friday': 4, 'Saturday': 5, 'Sunday': 6, } # Our list of suspects possibleDays = [] # Treat teenth specially(does anyone actually say that?) # I don't like this, it looks all ugly :( if suffix == 'teenth': for day in dayList: if day.day in range(13, 19) and \ day.weekday() == dayDic[day_of_week]: meetupDay = day else: for day in dayList: # If it's the right day of the week and the right month, it's a suspect if day.weekday() == dayDic[day_of_week] and \ day.month == month: possibleDays.append(day) meetupDay = possibleDays[dateDic[suffix]] return meetupDay
def initialize_month_attendance(**kwargs): print 'initializing month_attendance' latest = ServiceReport.objects.latest('month').month year = kwargs['year'] if kwargs.has_key('year') else latest.strftime('%Y') month = kwargs['month'] if kwargs.has_key('month') else latest.strftime('%m') initial = [] mwlist = [] welist = [] cal = Calendar() for day in cal.itermonthdates(int(year),int(month)): print 'day: %s' % day.isoformat() meeting = None if day.weekday()==settings.MEETING_MIDWEEK: meeting = "MW" mwlist.append({'meeting': meeting, 'meeting_date': day}) if day.weekday()==settings.MEETING_WEEKEND: meeting = "WE" welist.append({'meeting': meeting, 'meeting_date': day}) initial = mwlist + welist return initial
def meetup_date(year, month, nth=4, weekday=3): """Generate meetup date for given year, month, optional week, optional weekday :param year: :param month: :param nth: :param weekday: :return: meetup date in datetime.date format """ cal = Calendar() week = 0 dates = [] for day in cal.itermonthdates(year, month): if day.weekday( ) == weekday and day.year == year and day.month == month: week += 1 dates.append(datetime.date(year, month, day.day)) if nth > 0: return dates[nth - 1] else: return dates[nth]
def calendario_mes(request,curso_id,ano,mes): ano = int(ano) mes = int(mes) cal = HTMLCalendar() dias_semana = [] curso = Curso.objects.get(id=curso_id) for clase in curso.clase_set.all(): dias_semana.append(clase.dia_semana-1) dias_clase = [] c = Calendar() for d in c.itermonthdates(ano,mes): ##print d if d.weekday() in dias_semana: #evitamos recibir los dias que no son del mes que toca if d.month == mes: dias_clase.append(d.day) cal = ClasesCalendar(dias_clase) calendario = cal.formatmonth(ano,mes) return render_to_response('cursos/mes.html', {'calendario': calendario, "ano": ano, "mes": mes})
sheet["B3"].border = border sheet["B3"].font = font sheet["B3"].alignment = alignment sheet["C3"].value = '曜日' sheet["C3"].fill = fill_head sheet["C3"].border = border sheet["C3"].font = font sheet["C3"].alignment = alignment sheet["D3"].value = '祝日' sheet["D3"].fill = fill_head sheet["D3"].border = border sheet["D3"].font = font sheet["D3"].alignment = alignment r = 4 for date in cal.itermonthdates(now_year, now_month): if date.month == now_month: if date.weekday() == 5 or date.weekday() == 6: sheet.cell(row=r, column=2).fill = fill_weekend sheet.cell(row=r, column=3).fill = fill_weekend sheet.cell(row=r, column=4).fill = fill_weekend elif jpholiday.is_holiday_name(date) is not None: sheet.cell(row=r, column=2).fill = fill_holiday sheet.cell(row=r, column=3).fill = fill_holiday sheet.cell(row=r, column=4).fill = fill_holiday sheet.cell(row=r, column=2).value = date sheet.cell(row=r, column=2).border = border sheet.cell(row=r, column=3).value = w_list[date.weekday()] sheet.cell(row=r, column=3).border = border sheet.cell(row=r, column=4).value = jpholiday.is_holiday_name(date) sheet.cell(row=r, column=4).border = border
def main(year): # connect to the database print('Connecting to the database..') engine = create_engine( 'postgresql+psycopg2://postgres:{}@pg/mumtdw'.format( POSTGRES_PASSWORD)) connect = engine.connect() metadata = MetaData() date_table = Table('dates', metadata, autoload=True, autoload_with=engine) quarters = { 1: 1, 2: 1, 3: 1, 4: 2, 5: 2, 6: 2, 7: 3, 8: 3, 9: 3, 10: 4, 11: 4, 12: 4 } fc_quarters = { 1: 2, 2: 2, 3: 2, 4: 3, 5: 3, 6: 3, 7: 4, 8: 4, 9: 4, 10: 1, 11: 1, 12: 1 } c = Calendar() newyear_date = date(year, 1, 1) for month in range(1, 13): for d in c.itermonthdates(year, month): if d.year == year: if connect.execute( select([date_table]).where( and_(date_table.c.day == d.day, date_table.c.month == d.month, date_table.c.gregorian_year == d.year))).fetchone(): continue else: if d.month != month: continue from_newyear = d - newyear_date if d.month < 9: fiscal_year = d.year - 1 else: fiscal_year = d.year date_id = str(d.year) + '{0:02d}'.format( d.month) + '{0:02d}'.format(d.day) date_id = int(date_id) ins = date_table.insert().values( date_id=date_id, day=d.day, month=d.month, month_name=d.strftime('%B'), quarter=quarters[d.month], fc_quarter=fc_quarters[d.month], gregorian_year=d.year, day_of_year=from_newyear.days + 1, day_of_week=d.weekday() + 1, buddhist_year=d.year + 543, fiscal_year=fiscal_year, weekday=d.strftime('%A')) result = connect.execute(ins)
from datetime import datetime now = datetime.now() year, month = now.year, now.month from calendar import Calendar def consumed_hours(): from numpy.random import normal return round(normal(10.5, 0.7), 1) cal = Calendar() for d in cal.itermonthdates(year, month): if d.month != month: print '%5s'%('%d/%d'%(d.month, d.day)), else: print '%5d'%d.day, if d.weekday() >= 6: print print ' '.join(['%5.1f'%consumed_hours() for _ in range(5)]), print ' '.join(['%5s'%'-' for _ in range(2)]) print '-'*42
def _get_date_list(self, data): _cal = Calendar(5) _date = list( _cal.itermonthdates(self._context.get('rpt_year'), self._context.get('rpt_month'))) return _date
def _get_date_list(self): _cal = Calendar(5) _date = list(_cal.itermonthdates(self._context.get('rpt_year'), self._context.get('rpt_month'))) return _date