def meetup_day(year, month, name, ordinal): wkday_dict = {'Monday':0, 'Tuesday':1, 'Wednesday':2, 'Thursday':3, 'Friday':4, 'Saturday':5, 'Sunday':6 } wkday = wkday_dict[name] cal = Calendar() date_list = [] for day_date, weekday in cal.itermonthdays2(year, month): if weekday == wkday and not day_date == 0: date_list.append(day_date) date_dict = {'1st':0, '2nd':1, '3rd':2, '4th':3, '5th':4} if ordinal in date_dict: day = date_list[date_dict[ordinal]] elif ordinal == 'teenth': for day_date in date_list: if 12 < day_date < 20: day = day_date elif ordinal == 'last': day = date_list[-1] return date(year, month, day)
def get_day(year: int, month: int, week: int, day_of_week: DayOfWeek) -> int: calendar = Calendar() return [ d for d in calendar.itermonthdays2(year, month) if d[0] and d[1] == day_of_week - 1 ][week][0]
def meetup_day(year, month, dow, criteria): target_day = DoW[dow] if criteria == "teenth": start_day = 13 elif criteria == "last": start_day = monthrange(year, month)[1] - 6 elif criteria.startswith("1"): start_day = 1 elif criteria.startswith("2"): start_day = 8 elif criteria.startswith("3"): start_day = 15 elif criteria.startswith("4"): start_day = 22 elif criteria.startswith("5"): start_day = 29 else: raise KeyError cal = Calendar(datetime(year, month, 1).weekday()) dates = cal.itermonthdays2(year, month) for day in dates: if day[0] >= start_day: if day[1] == target_day: return date(year, month, day[0]) raise IndexError
def meetup_day(year, month, day_of_week, classifier): fns = { 'first': lambda x, _: x == 1, '1st': lambda x, _: x == 1, '2nd': lambda x, _: x == 2, '3rd': lambda x, _: x == 3, '4th': lambda x, _: x == 4, '5th': lambda x, _: x == 5, 'teenth': lambda _, y: 13 <= y <= 19 } cal = Calendar() month_day_names = [(day_num, day_name[weekday]) for day_num, weekday in cal.itermonthdays2(year, month) if 1 <= day_num <= 31] if classifier == 'last': month_day_names = reversed(month_day_names) classifier = 'first' elif classifier.endswith('teenth'): classifier = 'teenth' counter = 0 for day_num, weekday in month_day_names: if weekday == day_of_week: counter += 1 if fns[classifier](counter, day_num): return date(year, month, day_num) raise Exception('meetup day not found!')
def meetup_day(year, month, day, choice): ordinal_dict = {'1st': 1, '2nd': 2, '3rd': 3, '4th': 4} weekday_dict = {'Monday': 0, 'Tuesday': 1, 'Wednesday': 2, 'Thursday': 3, 'Friday': 4, 'Saturday': 5, 'Sunday': 6} calendar = Calendar() possibilities = list(calendar.itermonthdays2(year, month)) if choice in ordinal_dict: current_ordinal = 0 for possible_date in possibilities: if possible_date[0] != 0 and possible_date[1] == weekday_dict[day]: current_ordinal += 1 if current_ordinal == ordinal_dict[choice]: return date(year, month, possible_date[0]) elif choice == 'last': for possible_date in possibilities: if possible_date[0] != 0 and possible_date[1] == weekday_dict[day]: target_date = possible_date[0] return date(year, month, target_date) elif choice == 'teenth': for possible_date in possibilities: if possible_date[0] in range(13, 20) and \ possible_date[1] == weekday_dict[day]: return date(year, month, possible_date[0])
def meetup_day(year, month, day, recurance): cal = Calendar() days = list(day_name) days_of_week = {days[i]: i for i in range(0, len(days))} meetup_dow = days_of_week[day] days_in_month = cal.itermonthdays2(year, month) count = 0 meetup_date = None for day in days_in_month: if (day[0] != 0 and day[1] == meetup_dow): count = count + 1 if (recurance is 'teenth' and day[0] in range(13, 20)): return date(year, month, day[0]) elif (recurance is '1st' and count == 1): return date(year, month, day[0]) elif (recurance is '2nd' and count == 2): return date(year, month, day[0]) elif (recurance is '3rd' and count == 3): return date(year, month, day[0]) elif (recurance is '4th' and count == 4): return date(year, month, day[0]) else: meetup_date = date(year, month, day[0]) return meetup_date
def meetup_day(year, month, name, ordinal): wkday_dict = { 'Monday': 0, 'Tuesday': 1, 'Wednesday': 2, 'Thursday': 3, 'Friday': 4, 'Saturday': 5, 'Sunday': 6 } wkday = wkday_dict[name] cal = Calendar() date_list = [] for day_date, weekday in cal.itermonthdays2(year, month): if weekday == wkday and not day_date == 0: date_list.append(day_date) date_dict = {'1st': 0, '2nd': 1, '3rd': 2, '4th': 3, '5th': 4} if ordinal in date_dict: day = date_list[date_dict[ordinal]] elif ordinal == 'teenth': for day_date in date_list: if 12 < day_date < 20: day = day_date elif ordinal == 'last': day = date_list[-1] return date(year, month, day)
def get_days_and_dow(year_and_month: date) -> List: calendar = Calendar() days_and_dow = calendar.itermonthdays2(year_and_month.year, year_and_month.month) dow_text = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] days_and_dow_text = [(dow_text[dd[1]], dd[0]) for dd in days_and_dow if not dd[0] == 0] return days_and_dow_text
def meetup_day(year, month, day, ordinal): # Gets day of week number day = [ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" ].index(day) # Converts the ordinal to a number ordinal = ["teenth", "1st", "2nd", "3rd", "4th", "5th", "last"].index(ordinal) # Used to count number of day found count = 0 # Calendar used to get a list of days for specified month c = Calendar() # If we're searching for the last day of the month we search backwards if ordinal == 6: for d in list(c.itermonthdays2(year, month))[::-1]: # Skips days belonging to other months if d[0] == 0: continue # Returns date as soon as we find the day if d[1] == day: return datetime.date(year, month, d[0]) # Iterates days of specified months for d in c.itermonthdays2(year, month): # Skips days belonging to other months if d[0] == 0: continue # Checks if current day is a teenth day if we're searching for one if ordinal == 0: if d[0] in range(13, 20): if d[1] == day: return datetime.date(year, month, d[0]) # Increments count if day of the week we're searching is found if d[1] == day: count += 1 # Returns date if specified day is found if count == ordinal and count != 0: return datetime.date(year, month, d[0]) # Raises exception if no day is found raise MeetupDayException()
def sundays_on_first(): count = 0 cal = Calendar() for year in range(1901, 2001): for month in range(1, 13): it = cal.itermonthdays2(year, month) for month_day in it: if month_day[0] == 1 and month_day[1] == 6: count += 1 return count
def _get_dates_by_weekday(year, month): """Return a dict with weekdays as keys and sorted days in the month as values.""" cal = Calendar() dates_by_weekday = defaultdict(list) for day_of_month, weekday in cal.itermonthdays2(year, month): if day_of_month == 0: continue dates_by_weekday[weekday].append(date(year, month, day_of_month)) return dates_by_weekday
def weekday_of_birth_date(date): """Takes a date object and returns the corresponding weekday string""" cal = Calendar() weekday_lookup = dict( (day_number, day) for day_number, day in enumerate(WEEKDAYS)) return [ weekday_lookup[day_of_week] for day_of_month, day_of_week in cal.itermonthdays2( date.year, date.month) if day_of_month == date.day ][0]
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 candidates = [ day_num for day_num, weekday in cal.itermonthdays2(year, month) if 1 <= day_num <= 31 and day_name[weekday] == day_of_week ] 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 election_cycle(dt): """Takes a datetime.date object and returns the election cycle year (as an integer) for that date.""" if dt.year % 2 == 0: if dt.month == 11: cal = Calendar() november_calendar = cal.itermonthdays2(dt.year, 11) is_october_day = lambda (dayofmonth, weekday): dayofmonth == 0 november_days = dropwhile(is_october_day, november_calendar) is_monday = lambda (dayofmonth, weekday): weekday == 0 is_not_monday = lambda daytuple: not is_monday(daytuple) election_tuesday = next( dropwhile(is_monday, dropwhile(is_not_monday, november_days))) election_date = date(dt.year, 11, election_tuesday[0]) print election_tuesday print election_date if dt > election_date: return dt.year + 2 else: return dt.year else: return dt.year else: return dt.year + 1
import calendar from calendar import Calendar # 返回一周内各天的名称 c1 = Calendar() #不指定参数的话默认星期一(0 is Monday) print("返回一周内各天的名称: ", list(c1.iterweekdays())) c2 = Calendar(firstweekday=calendar.SATURDAY) #指定今天是星期六 print("返回指定周几后一周内各天的名称: ", list(c2.iterweekdays())) # 返回指定年,月的所有天数,会自动加上月前与月后的天数来令到每周都不会缺少日期(比如10.31是周三,会补上11.1,11.2与11.3来补全这一周) # 返回的迭代器是以datetime.date为元素 print("返回指定年,月的所有天数(datetime.date): ", list(c2.itermonthdates(2018, 10))) # 返回指定年,月的所有天数,不会自动加上月前与月后的天数来令到每周都不会缺少日期,缺少的天数为设为0 # 返回的迭代器是以int为元素 print("返回指定年,月的所有天数(int): ", list(c2.itermonthdays(2018, 10))) # 返回指定年,月的所有天数,不会自动加上月前与月后的天数来令到每周都不会缺少日期,缺少的天数为设为0 # 返回的迭代器是以元组为元素, 元组里是(几号,星期x)这样 print("返回指定年,月的所有天数(tuple): ", list(c2.itermonthdays2(2018, 10))) # 以周为单位返回指定年,月的所有天数,会自动加上月前与月后的天数来令到每周都不会缺少日期(比如10.31是周三,会补上11.1,11.2与11.3来补全这一周) # 返回的列表是每七个datetime.date列表为元素 print("返回指定年,月的所有天数(tuple): ", c2.monthdatescalendar(2018, 10))
def get_startday(year): c = Calendar() for day in c.itermonthdays2(year, 1): if day[0] != 0: return day[1]
class FinnishFlagDays: def __init__(self, year=None): self.calendar = Calendar() self.year = year or datetime.now().year self.official_flag_days = { date(self.year, 2, 28): u'Kalevalan päivä eli suomalaisen ' u'kulttuurin päivä', date(self.year, 5, 1): u'Vappu eli suomalaisen työn päivä', self.getMothersOrFathersDay(month=5): u'Äitienpäivä', date(self.year, 6, 4): u'Puolustusvoimien lippujuhlan päivä eli ' u'Suomen marsalkka C.G.E. Mannerheimin ' u'syntymäpäivä', self.getMidsummersDay() - timedelta(1): u'Juhannusaatto, Suomen ' u'lipun päivä', self.getMidsummersDay(): u'Juhannuspäivä, Suomen lipun päivä', date(self.year, 12, 6): u'Itsenäisyyspäivä', } self.unofficial_flag_days = { date(self.year, 2, 5): u'J. L. Runebergin päivä', date(self.year, 3, 19): u'Minna Canthin eli tasa-arvon päivä', date(self.year, 4, 9): u'Mikael Agricolan päivä eli suomen kielen ' u'päivä', date(self.year, 4, 27): u'Kansallinen veteraanipäivä', date(self.year, 5, 12): u'J. V. Snellmanin päivä eli ' u'suomalaisuuden päivä', self.getFallenHeroesDay(): u'Kaatuneitten muistopäivä', date(self.year, 7, 6): u'Eino Leinon päivä eli runon ja suven ' u'päivä', date(self.year, 10, 10): u'Aleksis Kiven päivä eli suomalaisen ' u'kirjallisuuden päivä', date(self.year, 10, 24): u'Yhdistyneiden kansakuntien päivä', date(self.year, 11, 6): u'svenska dagen, ruotsalaisuuden päivä', self.getMothersOrFathersDay(month=11): u'Isänpäivä', date(self.year, 12, 8): u'Jean Sibeliuksen päivä eli suomalaisen ' u'musiikin päivä', } def __call__(self, *args, **kwargs): all_flag_days = {} all_flag_days.update(self.official_flag_days) all_flag_days.update(self.unofficial_flag_days) return all_flag_days def getMothersOrFathersDay(self, month): """ Returns mothers day for the given year. If there is no year given, defaults to current year. - Finnish mothers day is second Sunday in May. - Finnish fathers day is second Sunday in November. """ counter = 0 for (day, weekday) in self.calendar.itermonthdays2(self.year, month): if weekday == 6: if counter == 0: counter += 1 else: return date(self.year, month, day) def getMidsummersDay(self): """ Returns midsummerday for the given year. If there is no year given, defaults to current year. - Midsummers day is the Saturday between 20. and 26. days in June. """ for (day, weekday) in self.calendar.itermonthdays2(self.year, 6): if day >= 20: if day <= 26: if weekday == 5: return date(self.year, 6, day) def getFallenHeroesDay(self): """ Returns date for flagging people fallen in war. - Mays third Sunday. """ counter = 0 for (day, weekday) in self.calendar.itermonthdays2(self.year, 5): if weekday == 6: if counter < 2: counter += 1 else: return date(self.year, 5, day) def sortFlagDays(self, days_dict): """Returns a list of tuples which contains flagdays in sorted order.""" return sorted(days_dict.iteritems()) def printFlagDays(self, flagdays): sorted_days = self.sortFlagDays(flagdays) for day in sorted_days: print "%s: %s" % (day[0].strftime('%d.%m.%Y'), day[1]) def printAllFlagDays(self): print("Official flag days") self.printFlagDays(flagdays=self.official_flag_days) print("\nUnofficial flag days") self.printFlagDays(flagdays=self.unofficial_flag_days) def isFlagday(self, date): """ Returs flagday name for the given date. Returns False if date is not flagday. """ if date in self.official_flag_days.keys(): return self.official_flag_days[date] elif date in self.unofficial_flag_days.keys(): return self.unofficial_flag_days[date] else: return False
from openpyxl import Workbook from calendar import Calendar workbook = Workbook() worksheet = workbook.active workbook.remove(worksheet) cal = Calendar() year = 2020 for m in range(1, 13): title = str(m) + "月份" sheet = workbook.create_sheet(title) month = cal.itermonthdays2(2020, m) row = 1 for day in month: print(day) if day[0] == 0: continue sheet.cell(row, 1, day[0]) sheet.cell(row, 2, day[1]) row += 1 workbook.save('2012年日历.xlsx')
print(calendar.leapdays(1900, 2100)) print(calendar.weekday(2019, 10, 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))
def imprimir_planilla_asistencia(self,ano,mes): ##Para la impresion de la planilla de asistencia a clase logging.debug("Vamos a imprimir la planilla de asistencia del mes %s del año %s"%(mes,ano)) fichero = get_print_path('Grupos')+"/Ficha_Asistencia_Mes%s_Grupo_%s.pdf"%(mes,self.g.id) calendario = Calendar(0) conversion = dict(lunes=0,martes=1,miercoles=2,jueves=3,viernes=4,sabado=5,domingo=6) iter_mes = calendario.itermonthdays2(ano,mes) ##Comprobamos si este mes es el inicio del curso try: res = Festivo.select(AND(Festivo.q.ano==ano,Festivo.q.mes==mes,Festivo.q.inicio==True)) inicio = res[0].dia logging.debug("El inicio del curso es el %s",inicio) except: ##No es el inicio, ponemos a la variable inicio a 0 así el día siempre será mayor que 0 inicio = 0 ##Comprobamos si este mes es el inicio del curso try: res = Festivo.select(AND(Festivo.q.ano==ano,Festivo.q.mes==mes,Festivo.q.fin==True)) fin = res[0].dia logging.debug("El fin de curso es el %s",fin) except: logging.debug("No es el fin") ##No es el fin, ponemos a la variable fin a 31 así el día siempre será menor que 31 fin = 31 estiloHoja = getSampleStyleSheet() story = [] ## ##Vamos con la cabecera ## banner = os.path.join(_config.get_data_path(), 'media', 'banner_eide.png') ## img=Image(banner) ## story.append(img) ##Intro estilo = estiloHoja['BodyText'] cadena = "<para alignment=center><b>RELACION DE DIAS LECTIVOS DEL MES %s %s</b></para>"%(nombre_mes(mes),ano) story.append(Paragraph(cadena, estilo)) story.append(Spacer(0,20)) ##Datos del docu: alumno, grupo, profes cadena = "Grupo: <b>%s - %s</b>"%(self.g.id,self.g.nombre) story.append(Paragraph(cadena, estilo)) cadena = "Curso: <b>%s</b>"%self.g.curso.nombre story.append(Paragraph(cadena, estilo)) cadena = "Numero de alumnos: <b>%s</b>"%len(self.g.alumnos) story.append(Paragraph(cadena, estilo)) story.append(Spacer(0,20)) ##Lista de libros for l in self.g.curso.libros: cadena = "Libro: %s - %s"%(l.titulo,l.autor)+" Editorial: %s "%(l.editorial) story.append(Paragraph(cadena, estilo)) cadena = " ISBN: %s"%(l.isbn) story.append(Paragraph(cadena, estilo)) story.append(Spacer(0,20)) ##Tabla con el horario tabla =[['Día','Horario','Aula','Profesor']] for c in self.g.clases: tabla.append([c.dia_semana,c.horario,"%s - %s"%(c.aula.numero,c.aula.piso),"%s %s"%(c.profesor.nombre,c.profesor.apellido1)]) t = Table(tabla) t.setStyle([('LINEABOVE', (0,0), (-1,0), 2, colors.black),('LINEBEFORE', (0,0), (0,-1), 2, colors.black), ('LINEABOVE', (0,1), (-1,-1), 0.25, colors.black),('LINEAFTER', (0,0), (-1,-1), 0.25, colors.black), ('LINEBELOW', (0,-1), (-1,-1), 2, colors.black),('LINEAFTER', (-1,0), (-1,-1), 2, colors.black), ('ALIGN', (1,1), (-1,-1), 'RIGHT')]) story.append(t) story.append(Spacer(0,20)) ##Tabla con los días fila = ['Num.','F. Nac.','Apellidos, Nombre','Cnf.'] dia_old = [] for dia in iter_mes: if dia[0] == 0: continue for clase in self.g.clases: if conversion[limpiar_tildes(clase.dia_semana).lower()] == dia[1] : ##Comprobamos si no es festivo res = Festivo.select(AND(Festivo.q.ano==ano,Festivo.q.mes==mes,Festivo.q.dia==dia[0],Festivo.q.inicio==False,Festivo.q.fin==False)) if not len(list(res)): ##Comrpobamos si ya hemos añadido ese día por tener 2h ##FIXME if dia == dia_old: debug("Ya habiamos añadido este día!") ##Sino comprobamos que el día sea después del inicio y antes del fin elif ( dia[0] >= inicio and dia[0] <= fin ): fila.append("%i"%(dia[0])) else: debug("El día %s esta antes o despues del inicio del curso!"%dia[0]) else: debug("El día %s es festivo"%dia[0]) dia_old = dia longitud = len(fila) relleno = longitud - 3 tabla =[fila] for asis in sorted(self.g.alumnos,key= lambda a: a.alumnoID): a = asis.alumno fila_alumno = [a.id,a.fecha_nacimiento,"%s %s, %s"%(a.apellido1,a.apellido2,a.nombre),asis.confirmado] while not len(fila_alumno)==longitud: fila_alumno.append(" ") tabla.append(fila_alumno) t = Table(tabla) t.setStyle([('LINEABOVE', (0,0), (-1,0), 2, colors.black),('LINEBEFORE', (0,0), (0,-1), 2, colors.black), ('LINEABOVE', (0,1), (-1,-1), 0.25, colors.black),('LINEAFTER', (0,0), (-1,-1), 0.25, colors.black), ('LINEBELOW', (0,-1), (-1,-1), 2, colors.black),('LINEAFTER', (-1,0), (-1,-1), 2, colors.black), ('ALIGN', (1,1), (-1,-1), 'RIGHT'),('FONTSIZE',(0,0),(-1,-1),8),('FONTSIZE',(2,0),(2,-1),9)]) story.append(t) story.append(Spacer(0,20)) ## story.append(Spacer(0,240)) ## ##Pie de página ## cadena="<para alignment=center><b>Genaro Oraá,6 - 48980 SANTURTZI (Spain)- Tlf. + 34 944 937 005 - FAX +34 944 615 723</b></para>" ## story.append(Paragraph(cadena, estilo)) ## cadena="<para alignment=center><b><a href=\"http:\\www.eide.es\">www.eide.es</a> - e-mail: [email protected]</b></para>" ## story.append(Paragraph(cadena, estilo)) ## story.append(Spacer(0,20)) ##Sacamos el docu doc=SimpleDocTemplate(fichero,pagesize=A4) doc.build(story) send_to_printer(fichero) return
#!/usr/env/python -tt from calendar import Calendar if __name__ == '__main__': cal = Calendar() r = 0 for y in xrange(1901, 2000 + 1): for m in xrange(1, 12 + 1): for d in cal.itermonthdays2(y, m): if d[0] == 1: if d[1] == 6: r += 1 break print r