def meetup_day(year,month,weekday,which): first = calendar.weekday(year,month,1) days = calendar.monthrange(year,month) weekday_ref={'Monday':0,'Tuesday':1,'Wednesday':2,'Thursday':3,'Friday':4,'Saturday':5,'Sunday':6} week=weekday_ref[weekday] if which=='1st': day_from=1 day_to=7 elif which=='2nd': day_from=8 day_to=14 elif which=='3rd': day_from=15 day_to=21 elif which=='4th': day_from=22 day_to=28 elif which=='5th': day_from=29 day_to=days[1] elif which=='last': day_from=days[1]-6 day_to=days[1] elif which=='teenth': day_from=13 day_to=19 for i in range(day_from,day_to+1): if calendar.weekday(year,month,i)==week: day=i return date(year,month,day)
def print_buttons(self): """ prints a set of interactive buttons corresponding to the date of the month currently selected :param self: member function of class Window """ self.cal_dates.destroy() self.btn_array = [] self.cal_dates = Frame(self.cal_frame, bg='white') self.cal_dates.grid(row=2, column=0) self.su_label = Label(self.cal_dates, text='Su', bg='white') self.su_label.grid(row=0, column=0) self.mo_label = Label(self.cal_dates, text='Mo', bg='white') self.mo_label.grid(row=0, column=1) self.tu_label = Label(self.cal_dates, text='Tu', bg='white') self.tu_label.grid(row=0, column=2) self.we_label = Label(self.cal_dates, text='We', bg='white') self.we_label.grid(row=0, column=3) self.th_label = Label(self.cal_dates, text='Th', bg='white') self.th_label.grid(row=0, column=4) self.fr_label = Label(self.cal_dates, text='Fr', bg='white') self.fr_label.grid(row=0, column=5) self.sa_label = Label(self.cal_dates, text='Sa', bg='white') self.sa_label.grid(row=0, column=6) grid_width = 7 index = 9 row = 1 # checks what day of week the first day of the month falls on if calendar.weekday(self.year, self.month, 1) == 6: column = 0 else: column = calendar.weekday(self.year, self.month, 1) + 1 # print the dates as buttons and bind them to a method while index < len(self.cal_data): new_button = Button(self.cal_dates, text=self.cal_data[index], relief=FLAT, width=5, bg='white', command=lambda opt=int(self.cal_data[index]): self.select_day(opt) ) self.btn_array.append(new_button) new_button.grid(row=row, column=column, sticky='E' + 'W') index += 1 column += 1 if column == grid_width: column = 0 row += 1
def printTrades(self, lotSizeInUSD=1000000, commissionPerPip=0): for position in self.closedPositions: p = ( position.closePrice - position.order.price ) * position.order.orderType * lotSizeInUSD - commissionPerPip if position.order.orderType == 1: print "%s long %s, %s, %.5f, %.5f, %.2f, %.2f dow:%d" % ( position.order.instrument, position.openTime, position.closeTime, position.openPrice, position.closePrice, p, (position.closePrice - position.order.price) * position.order.orderType / 0.0001, calendar.weekday(position.openTime.year, position.openTime.month, position.openTime.day), ) else: print "%s short %s, %s, %.5f, %.5f, %.2f, %.2f dow:%d" % ( position.order.instrument, position.openTime, position.closeTime, position.openPrice, position.closePrice, p, (position.closePrice - position.order.price) * position.order.orderType / 0.0001, calendar.weekday(position.openTime.year, position.openTime.month, position.openTime.day), )
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 holidayBreak(year): first_day = 23 last_day = 31 + 1 # first day of the break weekday = calendar.weekday(year, 12, 23) if weekday == 0: first_day -= 2 elif weekday == 1: first_day -= 3 elif weekday == 2: first_day -= 4 elif weekday == 6: first_day -= 1 # last day of the break weekday = calendar.weekday(year + 1, 1, 1) if weekday == 6 or weekday == 5: last_day += 1 elif weekday == 4: last_day += 2 elif weekday == 3: last_day += 3 elif weekday == 2: last_day += 4 return last_day - first_day + 1
def _displayMonth( self): id=self._id type=self._type month = self._month year = self._year today = date.today() res = [] url = urlHandlers.UHGetCalendarOverview.getURL() url.addParam("selCateg", id) url.addParam("period",type) nextMonth= urlHandlers.UHGetCalendarOverview.getURL() previousMonth= urlHandlers.UHGetCalendarOverview.getURL() nextYear= urlHandlers.UHGetCalendarOverview.getURL() previousYear= urlHandlers.UHGetCalendarOverview.getURL() nextMonth.addParam("selCateg", id) previousMonth.addParam("selCateg", id) nextYear.addParam("selCateg", id) previousYear.addParam("selCateg", id) nextMonth.addParam("period",type) previousMonth.addParam("period",type) nextYear.addParam("period",type) previousYear.addParam("period",type) for day in range(1,calendar.monthrange(year,month)[1]+1): if day == 1: for i in range(calendar.weekday(year,month,day)): res.append("<td></td>") if calendar.weekday(year,month,day) in (5,6): bgcolor="#e0cdcd" else: bgcolor="#FFFFFF" if self._date != []: #for highlight multiple dates for date2 in self._date: (d,m,y) = date2.split("-") try: if date(year,month,day) == date(int(y),int(m),int(d)): bgcolor="#ffcccc" except Exception,e: raise "%s-%s-%s------%s-%s-%s\nself._date:%s\ndate2:%s"%(year,month,day,y,m,d, self._date,date2) url.addParam("day", day) url.addParam("month",month) url.addParam("year", year) strUrl = "%s"%url if date(year,month,day) == today: bgcolor="#ccffcc" res.append( """<td align="right" bgcolor="%s"><a href="%s">%s</a></td>"""%(bgcolor,strUrl,day )) if calendar.weekday(year,month,day) == 6: res.append("</tr><tr>")
def is_valid_date(given_date): """ Given a date string this function checks if the date is in the future """ given_date = given_date.split("/") current_date = get_current_date().split("/") given_day = int(given_date[1]) given_month = int(given_date[0]) given_year = int(given_date[2]) current_day = int(current_date[1]) current_month = int(current_date[0]) current_year = int(current_date[2]) try: calendar.weekday(given_year, given_month, given_day) except ValueError: return False return ( (given_year == current_year and given_month == current_month and given_day > current_day) or (given_year == current_year and given_month > current_month) or (given_year > current_year))
def meetup_day(yr, mo, da, mod): cal = calendar.Calendar() daydict = { "Sunday": 6, "Monday": 0, "Tuesday": 1, "Wednesday": 2, "Thursday": 3, "Friday": 4, "Saturday": 5 } date_actual = None daylist = [x for x in cal.itermonthdays(yr, mo) if x!= 0] dates = [] if mod == "teenth": daterange = [x for x in list(range(13, 20))] for d in daterange: if dt.date(yr, mo, d).weekday() == daydict[da]: date_actual = dt.date(yr, mo, d) if mod in ["1st", "2nd", "3rd", "4th", "5th"]: posdict = { "1st": 1, "2nd": 2, "3rd": 3, "4th": 4, "5th": 5 } counter = 0 for x in daylist: if calendar.weekday(yr, mo, x) == daydict[da] and counter < posdict[mod]: dates.append(x) counter += 1 elif counter == posdict[mod]: date_actual = dt.date(yr, mo, max(dates)) if mod == "last": for x in daylist: if calendar.weekday(yr, mo, x) == daydict[da]: dates.append(x) date_actual = dt.date(yr, mo, max(dates)) if date_actual == None: raise Exception else: return date_actual
def independence_day(year, observed=None): '''July 4th''' day = 4 if observed: if calendar.weekday(year, JUL, 4) == SAT: day = 3 if calendar.weekday(year, JUL, 4) == SUN: day = 5 return (year, JUL, day)
def most_frequent_days(year): freq_day = [] first = calendar.weekday(year, 1, 1) last = calendar.weekday(year, 12, 31) if first == last: freq_day.append(calendar.day_name[first]) elif first > last: freq_day.append(calendar.day_name[last]), freq_day.append(calendar.day_name[first]) else: freq_day.append(calendar.day_name[first]), freq_day.append(calendar.day_name[last]) return freq_day
def _displayMonth( self ): month = self._month year = self._year today = date.today() res = [] for day in range(1,calendar.monthrange(year,month)[1]+1): if day == 1: for i in range(calendar.weekday(year,month,day)): res.append("<td></td>") #calendar.weekday(year,month,day) in (5,6): if HolidaysHolder.isWorkingDay( datetime( year, month, day ) ): bgcolor="#FFFFFF" else: bgcolor="#EEEEEE" if date(year,month,day) == today: bgcolor="#ccffcc" if self._date != '': (d,m,y) = self._date.split("-") if date(year,month,day) == date(int(y),int(m),int(d)): bgcolor="#ffcccc" res.append( """<td align="right" bgcolor="%s"><a href="" onClick="SetDate(%s,%s,%s);">%s</a></td>"""%(bgcolor,day,month,year,day )) if calendar.weekday(year,month,day) == 6: res.append("</tr><tr>") str = _(""" <table> <tr> <td colspan="7" align="center"><b> <a href="javascript:PreviousYear();"><<</a> <a href="javascript:PreviousMonth();"><</a> %s %s <a href="javascript:NextMonth();">></a> <a href="javascript:NextYear();">>></a> </b></td> </tr> <tr> <td align="right" bgcolor="#CCCCCC">_("Mo")</td> <td align="right" bgcolor="#CCCCCC">_("Tu")</td> <td align="right" bgcolor="#CCCCCC">_("We")</td> <td align="right" bgcolor="#CCCCCC">_("Th")</td> <td align="right" bgcolor="#CCCCCC">_("Fr")</td> <td align="right" bgcolor="#CCCCCC">_("Sa")</td> <td align="right" bgcolor="#CCCCCC">_("Su")</td> </tr> <tr> %s </tr> </table> """) %(datetime(1900,month,1).strftime("%B"), year, "\n".join(res)) return str
def align_date_to_week(date, timezone, direction): """ Like :func:`align_date_to_day`, but for weeks. The first day of the week is monday. """ date = align_date_to_day(date, timezone, direction) if direction == 'down': return date - timedelta( days=weekday(date.year, date.month, date.day)) else: return date + timedelta( days=6 - weekday(date.year, date.month, date.day))
def dateRange(self, daysPadding): # daysPadding is in days import datetime if self.d == 0: # handle the case the day is 0 (day wasn't indicated on wikipedia page) self.d = 1 date = datetime.date(int(self.y), int(self.m), int(self.d)) difference = datetime.timedelta(days=daysPadding) beginInterval = date - difference endInterval = date + difference earliestDate = datetime.date(1985, 9, 2) # earliest borderline check if beginInterval < earliestDate: beginInterval = earliestDate endInterval = beginInterval + difference + difference beginDate = Date(str(beginInterval.month) + "-" + str(beginInterval.day) + "-" + str(beginInterval.year)) endDate = Date(str(endInterval.month) + "-" + str(endInterval.day) + "-" + str(endInterval.year)) # make sure none of dates returned are weekends import calendar if calendar.weekday(beginDate.y, beginDate.m, beginDate.d) == 6: # beginDate is Sunday # print 'beginDate is Sunday' difference = datetime.timedelta(days=2) date = datetime.date(int(beginDate.y), int(beginDate.m), int(beginDate.d)) beginInterval = date - difference elif calendar.weekday(beginDate.y, beginDate.m, beginDate.d) == 5: # beginDate is Saturday # print 'beginDate is Saturday' difference = datetime.timedelta(days=1) date = datetime.date(int(beginDate.y), int(beginDate.m), int(beginDate.d)) beginInterval = date - difference if calendar.weekday(endDate.y, endDate.m, endDate.d) == 6: # endDate is Sunday # print 'endDate is Sunday' difference = datetime.timedelta(days=1) date = datetime.date(int(endDate.y), int(endDate.m), int(endDate.d)) endInterval = date + difference elif calendar.weekday(endDate.y, endDate.m, endDate.d) == 5: # endDate is Saturday # print 'endDate is Saturday' difference = datetime.timedelta(days=2) date = datetime.date(int(endDate.y), int(endDate.m), int(endDate.d)) endInterval = date + difference # begin interval is a weekend: beginDate = Date(str(beginInterval.month) + "-" + str(beginInterval.day) + "-" + str(beginInterval.year)) endDate = Date(str(endInterval.month) + "-" + str(endInterval.day) + "-" + str(endInterval.year)) # print self # print beginDate # print endDate return (beginDate, endDate)
def work_hours(start, end=None): """ Calculates work hours count beetween two dates If end is None, calcs from current to end """ from_now = False if not end: from_now = True end = start start = datetime.datetime.today().date() if end < start: raise Exception('End is before Start') days = 0 iter = start while iter != end: if calendar.weekday(iter.year, iter.month, iter.day) in xrange(5): days += 1 iter += datetime.timedelta(days=1) if from_now: if datetime.datetime.now().time() < datetime.time(20, 00): days += 1 else: days += 1 return days * 8
def count_monday(): count = 0 for yyyy in range(2015,2017): for mm in range(1,13): if(calendar.weekday(yyyy,mm,01)==0): count=count+1 print count
def reserve_interval(backups, type, num): ''' given a list of backup filenames, interval type(monthly, weekly, daily), and the number of backups to keep, return a list of filenames to reserve. ''' result = [] now = datetime.now() if type == 'monthly': delta = timedelta(30) interval_end = datetime(now.year, now.month, 1) # begin of the month interval_start = interval_end - delta elif type == 'weekly': delta = timedelta(7) weekday = calendar.weekday(now.year, now.month, now.day) weekday_delta = timedelta(weekday) interval_end = datetime(now.year, now.month, now.day) - weekday_delta # begin of the week interval_start = interval_end - delta elif type == 'daily': delta = timedelta(1) interval_end = datetime(now.year, now.month, now.day) + delta interval_start = interval_end - delta for i in range(1, num + 1): for backup in backups: if between_interval(backup, interval_start, interval_end): result.append(backup) break # reserve only one backup per interval interval_end = interval_end - delta interval_start = interval_start - delta return result
def __get_exif_date(self, path, tag): ext = os.path.splitext(path)[1][1:].lower() if re.match('tif|tiff|jpg|jpeg|jtif|thm', ext, re.IGNORECASE): try: file = open(path, 'rb') except IOError: self.__add_to_errors(path, _(u"Could not open file!")) else: tags = EXIF.process_file(file, details=False, stop_tag=tag) # see if the tag exists if tags.has_key(tag): try: itemDateTime = str(tags[tag]) itemDateTime = re.compile(r'\D').split(itemDateTime) itemDateTime = map(int, itemDateTime) except ValueError, err: self.__add_to_warnings(path, _(u"Exif error: %s") % err) return False # attempt to convert tag's text to a date try: dayWeek = calendar.weekday(itemDateTime[0], itemDateTime[1], itemDateTime[2]) # invalid date except ValueError, err: self.__add_to_warnings(path, _(u"Exif error: %s") % err) else: itemDateTime.extend([dayWeek, 1, 0]) return itemDateTime
def gen_data_list_by_day_of_week(list_data): # params: data list from txt file # obj: separate draw data into Wed, Sat, Sun, Special draw day # return: a list containing 4 list element, [wed, sat, sun, other] list_wed_draw = [] list_sat_draw = [] list_sun_draw = [] list_other_draw = [] #list to store draw result for Wed, Sat, Sun and other day dict_draw_day_list = {2:list_wed_draw, 5:list_sat_draw, 6:list_sun_draw} for each_data_set in list_data: # [["19970101", "4102", "5257", "0061"],.... # extract year, month, day from data and use calendar.weekday() to determine day of the week year = int(each_data_set[0][:4]) month = int(each_data_set[0][4:6]) day = int(each_data_set[0][6:]) day_of_week = weekday(year,month,day) if day_of_week in dict_draw_day_list: dict_draw_day_list[day_of_week].append(each_data_set) else: list_other_draw.append(each_data_set) return [list_wed_draw, list_sat_draw, list_sun_draw, list_other_draw]
def run(): # cheating :) sundays = sum(calendar.weekday(year, month, 1) == calendar.SUNDAY for year in range(1901, 2001) for month in range(1, 13)) print(sundays)
def getWorkDayInfo(self,custemDayInfo): dateArrary=[] wkdayArrary=[] dateFlagArrary=[] monthrange = calendar.monthrange(self.YearAndMonth[0],self.YearAndMonth[1]) #Add 0 before string to avoid format error str_month = str(self.YearAndMonth[1]) if int(str_month)<10: str_month = '0'+str_month for i in range(monthrange[1]): day = i+1 if day<10: str_day = "0"+str(day) else: str_day = str(day) dateString = str(self.YearAndMonth[0])+"/"+str_month+"/"+str_day dateArrary.append(dateString) wkd_int = calendar.weekday(self.YearAndMonth[0], self.YearAndMonth[1], day) wkdayArrary.append(wkcalendarMap[str(wkd_int)]) if wkd_int in [5,6]: flag = False else: flag = True #print dateString if dateString in custemDayInfo['vacationConfig']['vacation']: flag = False elif dateString in custemDayInfo['vacationConfig']['work day']: flag = True dateFlagArrary.append(flag) return (dateArrary,wkdayArrary,dateFlagArrary)
def get_lesson_dates_in_month(self, month, year): ''' Will be used to generate the scheduledlessons for a student Interval represents how many weeks between each lesson ''' first_of_month = datetime.date(month=month, year=year, day=1) found_first_date = False first_date = first_of_month # get the first date that matches the day of the week while not found_first_date: day_of_week_index = calendar.weekday( first_date.year, first_date.month, first_date.day) if str(day_of_week_index) == self.day: found_first_date = True break first_date = first_date + datetime.timedelta(days=1) date = first_date dates_in_month = [] while date.month == month: dates_in_month.append(date) # Bug here! if period is anything besides 1, this will give # bad results. Putting 2 will cause issues in months after # those with 5 weeks date = date + datetime.timedelta(days=7*self.period) return dates_in_month
def approach2(): total = 0 for y in range(1901,2001): for m in range(1,13): if(calendar.weekday(y,m,1) == 6): total = total + 1 print total
def _init_heading_and_css_day_abbr(self): day_idx = calendar.weekday(self.first_moment.year, self.first_moment.month, self.first_moment.day) day_abbr = calendar.day_abbr[day_idx] self.heading = "%s %d/%d" % (day_abbr, self.last_moment.month, self.last_moment.day) self.css_day_abbr = self._css_day_abbr[day_idx]
def validateAiringDay(self,askedDate, show): for day in show.getAiringDays(): if calendar.weekday(askedDate.year, askedDate.month, askedDate.day) == time.strptime(day, '%a').tm_wday: return True error = ValueError("Date is not a show's airing day ") self.makeErrorBox(error) return False
def visualizations(event): """ Método que nos permite ir almacenando en el modelo Visualizations el número de eventos producidos en una hora de un determinado día para luego extraer dicha información en la vistas de la aplicación Args: event: Objeto de la BD que contiene información de un evento asociado de Iptables Returns: Almacena en el modelo Visualizations la información extraida del evento. """ # Creamos un objeto Visualizations con la informacion pasada como argumento al metodo try: visualizations = Visualizations.objects.get( Date=event['Date'], Hour=event['Hour'], ID_Source=LogSources.objects.get(Type='Iptables') ) number_events = visualizations.Process_Events + 1 Visualizations.objects.filter(pk=visualizations.pk).update(Process_Events=number_events) visualizations.refresh_from_db() # Sino hay un objeto o hay algun fallo en la creación del objeto se crea la estructura # completa en la bd except Visualizations.DoesNotExist: list_names_days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] year = event['Date'].year month = event['Date'].month day = event['Date'].day week_day = calendar.weekday(year, month, day) week_month = 0 count_week = 0 for it in calendar.Calendar(0).monthdayscalendar(year, month): if it.count(day) == 1: week_month = count_week else: count_week += 1 try: visualizations = Visualizations( Week_Month=week_month, Week_Day=week_day, Name_Day=list_names_days[week_day], Date=event['Date'], Hour=event['Hour'], ID_Source=LogSources.objects.get(Type='Iptables'), Process_Events=1, ) visualizations.save() except Exception as ex: print "visualizations -> ", ex print sys.exc_traceback.tb_lineno except Exception as ex: print "visualizations -> ", ex print sys.exc_traceback.tb_lineno
def days_Dates(start_date, stop_date, weekday, day): weekdays = 0 for i in range(start_date,stop_date+1): for j in range(1,13): if c.weekday(i,j,day) == weekday: weekdays += 1 return weekdays
def setRTCCalarm(year, month, date, hour, minute, second, mode): """Sets an alarm for a date and time using given values. Call the C version of the function using the DLL to set the alarm at the given date and time. """ # Check that the arguments are reasonable if year < 1900: # Cannot set the year to before the year 1900 print "Invalid year" return if month not in range(1, 13): # There are only 12 months in a year print "Invalid month" return if date not in range(1, 32): # There are at most 31 days in a month print "Invalid date" return if hour not in range(0, 24): # There are hours 0 to 23 in a 24 hour clock print "Invalid hour" return if minute not in range(0, 60): # There are 0 to 59 minutes in an hour print "Invalid minute" return if second not in range(0, 60): # There are 0 to 59 seconds in a minute print "Invalid second" return w_day = calendar.weekday(year, month, date) # Get the weekday for the given year, month, date # Set the values if valid to an alarm on the Sensorian Real Time Clock and Calendar lib_sensorian.set_rtcc_alarm(((year + 1900) - 2000) % 100, month, date, w_day, hour, minute, second, mode)
def countSundays(): sundayCount = 0 for year in range(1901,2001): for month in range(1,13): if (calendar.weekday(year, month, 1) == 6): sundayCount += 1 return sundayCount
def _get_complete_name(self, cr, uid, ids, name, args, context=None): ret = {} weekday_to_str = {0:'Lundi',1:'Mardi',2:'Mercredi',3:'Jeudi',4:'Vendredi',5:'Samedi',6:'Dimanche'} for line in self.browse(cr, uid, ids, context=context): dt_checkin = fields.datetime.context_timestamp(cr, uid, datetime.strptime(line.checkin,'%Y-%m-%d %H:%M:%S'), context=context) dt_checkout = fields.datetime.context_timestamp(cr, uid, datetime.strptime(line.checkout,'%Y-%m-%d %H:%M:%S'), context=context) checkin = dt_checkin.strftime('%Y-%m-%d %H:%M:%S') checkout = dt_checkout.strftime('%Y-%m-%d %H:%M:%S') weekday_start = calendar.weekday(int(checkin[:4]), int(checkin[5:7]), int(checkin[8:10])) weekday_end = calendar.weekday(int(checkout[:4]), int(checkout[5:7]), int(checkout[8:10])) date_str = '' if weekday_start <> weekday_end: date_str = '%s %s - %s %s : ' % (weekday_to_str[weekday_start][:3],checkin[11:16],weekday_to_str[weekday_end][:3],checkout[11:16]) ret[line.id] = '%s %d x %s (%s)' %(date_str,line.qte_reserves, line.reserve_product.name_template, line.partner_id.name) return ret
def checkdate(dt, d): # Check if the date is in the week where the 3rd friday of Mar/Jun/Sep/Dec # EuroStoxx50 expiry codes: MY # M -> H, M, U, Z (Mar, Jun, Sep, Dec) # Y -> 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 -> year code. 5 -> 2015 MONTHS = dict(H=3, M=6, U=9, Z=12) M = MONTHS[d._dataname[-2]] centuria, year = divmod(dt.year, 10) decade = centuria * 10 YCode = int(d._dataname[-1]) Y = decade + YCode if Y < dt.year: # Example: year 2019 ... YCode is 0 for 2020 Y += 10 exp_day = 21 - (calendar.weekday(Y, M, 1) + 2) % 7 exp_dt = datetime.datetime(Y, M, exp_day) # Get the year, week numbers exp_year, exp_week, _ = exp_dt.isocalendar() dt_year, dt_week, _ = dt.isocalendar() # print('dt {} vs {} exp_dt'.format(dt, exp_dt)) # print('dt_week {} vs {} exp_week'.format(dt_week, exp_week)) # can switch if in same week return (dt_year, dt_week) == (exp_year, exp_week)
print(time.strftime('%p %I:%M:%S', time.localtime())) # 달력 모듈 # 달력과 관련된 정보를 다루는 모듈 # calendar : 지정한 년도의 달력 출력 # prmonth : 지정한 월 달력 출력 # weekday : 지정한 일자의 달력 출력(0:월) # monthrange: 지정한 월의 첫날의 요일과 마지막날 출력 # isleap : 윤년 여부를 출력 import calendar as cal print(cal.calendar(2020)) print(cal.prmonth(2020, 6)) print(cal.weekday(2020, 6, 26)) print(cal.monthrange(2020, 6)) print(cal.isleap(2020)) print(cal.isleap(2019)) # 난수 생성 모듈 # 난수 생성과 표본 추출 기능을 제공 # randint : 지정한 범위내 난수 생성 # sample : 리스트에서 무작위 지정한 n개 항목 복원 추출 # choice : 리스트에서 무작위 항복 복원 추출 import random as r r.seed(20200626) # 일정한 난수가 생성되도록 초기화
""" Calendar Module You are given a date. Your task is to find what the day is on that date. The input is in `MM DD YYYY` format. """ import calendar if __name__ == '__main__': weekdays = { 0: "MONDAY", 1: "TUESDAY", 2: "WEDNESDAY", 3: "THURSDAY", 4: "FRIDAY", 5: "SATURDAY", 6: "SUNDAY" } month, day, year = map(int, input().rsplit()) print(weekdays[calendar.weekday(year, month, day)])
def solution(a, b): day=["MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN"] return day[calendar.weekday(2016, a, b)]
import calendar # С помощью модуля calendar узнайте, является ли 2030 год високосным leap = calendar.isleap(2030) if leap == 'True': print('2030 год будет викосным') else: print('2030 год НЕ будет викосным\n') # С помощью модуля calendar узнайте, каким днем недели # был день 25 июня 2000 года. day = calendar.weekday(2000, 6, 25) if day == 0: print('Понедельник') elif day == 1: print('Вторник') elif day == 2: print('Среда') elif day == 3: print('Четверг') elif day == 4: print('Пятница') elif day == 5: print('Суббота') else: print('Воскресенье')
import calendar #c=calendar.Calendar(0) #print(c.monthdays2calendar(2020,10)) calText = calendar.TextCalendar() print(calText.formatmonth(2021, 8)) #c = calendar.HTMLCalendar(0) #print(c.formatmonth(2020,10)) print(calendar.isleap(2021)) print(calendar.weekday(2022, 4, 21))
## calendar.calendar(연도)로 사용하면 그해의 전체 달력을 볼 수 있다. 결괏값은 달력이 너무 길어 생략하겠다. import calendar print(calendar.calendar(2021)) ## calendar.prcal(연도)를 사용해도 위와 똑같은 결괏값을 얻을 수 있다. calendar.prcal(2021) # 다음의 예는 2015년 12월의 달력만 보여준다. calendar.prmonth(2015, 12) ## calendar.weekday # calendar 모듈의 또 다른 유용한 함수를 보자. # weekday(연도, 월, 일) 함수는 그 날짜에 해당하는 요일 정보를 돌려준다. # 월요일은 0, 화요일은 1, 수요일은 2, 목요일은 3, 금요일은 4, 토요일은 5, 일요일은 6이라는 값을 돌려준다. calendar.weekday(2015, 12, 31) ## calendar.monthrange # monthrange(연도, 월) 함수는 입력받은 달의 1일이 무슨 요일인지와 그 달이 며칠까지 있는지를 튜플 형태로 돌려준다. calendar.monthrange(2015, 12) ##### random ### random은 난수(규칙이 없는 임의의 수)를 발생시키는 모듈이다. random과 randint에 대해 알아보자. # 다음은 0.0 에서 1.0사이의 실수 중에서 난수 값을 돌려주는 예를 보여준다. import random random.random() # 다음 예는 1에서 10사이의 정수 중에서 난수 값을 돌려준다. random.randint(1, 10)
from sys import stdin from calendar import weekday wd = { 0: 'Monday', 1: 'Tuesday', 2: 'Wednesday', 3: 'Thursday', 4: 'Friday', 5: 'Saturday', 6: 'Sunday' } for line in stdin: print(wd[weekday(2009, int(line.split()[1]), int(line.split()[0]))])
import calendar a = input('Введите вашу дату рождения в формате(день.месяц.год): ') data = a.split('.') d = calendar.weekday(int(data[2]), int(data[1]), int(data[0])) weekdays = [ 'Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота', 'Воскресенье' ] print(weekdays[d])
import calendar if __name__ == '__main__': day = list(map(int, input().split())) ans = calendar.weekday(day[2], day[0], day[1]) if ans == 0: print('MONDAY') elif ans == 1: print('TUESDAY') elif ans == 2: print('WEDNESDAY') elif ans == 3: print('THURSDAY') elif ans == 4: print('FRIDAY') elif ans == 5: print('SATURDAY') elif ans == 6: print('SUNDAY') # print((calendar.day_name[calendar.weekday(day[2], day[0], day[1])]).upper())
perc_missed, perc_missed_left, perc_missed_right = [],[],[] date_abbr,no_trials,session_length, mondays = [],[],[],[] n_rewards = [] for i,log_path in enumerate(log_paths): path = log_path.parent LogDf = bhv.get_LogDf_from_path(log_path) # Correct date format folder_name = os.path.basename(path) date_str = folder_name.split('_')[0].split('-') date = [int(d) for d in date_str] # Vertical lines on monday weekday = calendar.weekday(date[0],date[1],date[2]) if weekday == 0: mondays.append(i) month_abbr = calendar.month_abbr[date[1]] date_abbr.append(month_abbr+'-'+str(date[2])) # Getting metrics TrialSpans = bhv.get_spans_from_names(LogDf, "TRIAL_ENTRY_STATE", "ITI_STATE") TrialDfs = [] for i, row in tqdm(TrialSpans.iterrows(),position=0, leave=True): TrialDfs.append(bhv.time_slice(LogDf, row['t_on'], row['t_off'])) metrics = (met.get_start, met.get_stop, met.get_correct_side, met.get_outcome, met.get_chosen_side, met.has_choice) SessionDf = bhv.parse_trials(TrialDfs, metrics)
import calendar # get input - space separated numbers for month, day, year mo, dy, yr = map(int, input().split()) # create tuple with days of the week - this is a 'lookup' for converting # the number of the day into the string of the day weekdays = ('monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday') # use the calendar.weekday function to return the integer number of the day. day = weekdays[calendar.weekday(yr, mo, dy)] print(day.upper())
def _correct_for_time_frame(self, dateobj): days = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'] token_weekday, _ = getattr(self, '_token_weekday', (None, None)) if token_weekday and not (self._token_year or self._token_month or self._token_day): day_index = calendar.weekday(dateobj.year, dateobj.month, dateobj.day) day = token_weekday[:3].lower() steps = 0 if 'future' in self.settings.PREFER_DATES_FROM: if days[day_index] == day: steps = 7 else: while days[day_index] != day: day_index = (day_index + 1) % 7 steps += 1 delta = timedelta(days=steps) else: if days[day_index] == day: if self.settings.PREFER_DATES_FROM == 'past': steps = 7 else: steps = 0 else: while days[day_index] != day: day_index -= 1 steps += 1 delta = timedelta(days=-steps) dateobj = dateobj + delta if self.month and not self.year: try: if self.now < dateobj: if self.settings.PREFER_DATES_FROM == 'past': dateobj = dateobj.replace(year=dateobj.year - 1) else: if self.settings.PREFER_DATES_FROM == 'future': dateobj = dateobj.replace(year=dateobj.year + 1) except ValueError as e: if dateobj.day == 29 and dateobj.month == 2: valid_year = self._get_correct_leap_year( self.settings.PREFER_DATES_FROM, dateobj.year) dateobj = dateobj.replace(year=valid_year) else: raise e if self._token_year and len(self._token_year[0]) == 2: if self.now < dateobj: if 'past' in self.settings.PREFER_DATES_FROM: dateobj = dateobj.replace(year=dateobj.year - 100) else: if 'future' in self.settings.PREFER_DATES_FROM: dateobj = dateobj.replace(year=dateobj.year + 100) if self._token_time and not any([ self._token_year, self._token_month, self._token_day, hasattr(self, '_token_weekday') ]): if 'past' in self.settings.PREFER_DATES_FROM: if self.now.time() < dateobj.time(): dateobj = dateobj + timedelta(days=-1) if 'future' in self.settings.PREFER_DATES_FROM: if self.now.time() > dateobj.time(): dateobj = dateobj + timedelta(days=1) return dateobj
def draw_calendar(self, selected_date=None): """Creates the calendar days & labels (as buttons) and adds them to a list.""" if selected_date is None: now = datetime.datetime.now() else: current_date = datetime.datetime.now() if current_date.year == selected_date[ 0] and current_date.month == selected_date[1]: today = current_date.day else: today = 1 now = datetime.datetime(selected_date[0], selected_date[1], today) self.monthButton.setText('{m}, {y}'.format(m=self.MONTHS[now.month - 1], y=now.year)) # get days in current month days_in_month = calendar.monthrange(now.year, now.month)[1] # get days in previous month prev_month_info = self._get_next_month(go_forward=False) days_in_prev_month = calendar.monthrange(prev_month_info[0], prev_month_info[1])[1] # find what day of the week is the 1st of the month first_day_of_week = calendar.weekday(now.year, now.month, 1) # Before the new month is drawn, remove all previous widgets from the gridLayout for i in reversed(range(self.gridLayout.count())): self.gridLayout.itemAt(i).widget().setParent(None) # Now draw everything for the selected month for column in xrange(self.DAYS_NUM): for row in xrange(self.WEEKS_NUM): # First row is the labels for the days of the week if row == 0: day = self.DAYS_OF_WEEK[column] newButton = QtGui.QPushButton('{d}'.format(d=day)) if column < 5: newButton.setStyleSheet(stylesheet.WeekdayLabelStyle) else: # Highlight weekend in red newButton.setStyleSheet(stylesheet.WeekendLabelStyle) else: # Calculate they day number for the current position day = ((row - 1) * self.DAYS_NUM) + (column + 1) - first_day_of_week # Get day in previous month before we hit the first day of this month. # For example if the 1st of the month is on wednesday, calculate what day of the # previous month is on Monday & Tuesday etc. if row == 1 and column < first_day_of_week: # If we are before the first of the month, day will have a negative value=> we have to add to it # the days of the prev month in order to find the current day number day = days_in_prev_month + day # Add new button and append it to the list of buttons newButton = QtGui.QPushButton('{d}'.format(d=day)) newButton.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) newButton.setStyleSheet( stylesheet.OutsideMonthDaysStyle) else: if day > days_in_month: day = day - days_in_month # start counting the days from the next month # Add new button and append it to the list of buttons newButton = QtGui.QPushButton('{d}'.format(d=day)) newButton.setSizePolicy( QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) newButton.setStyleSheet( stylesheet.OutsideMonthDaysStyle) else: # Add new button and append it to the list of buttons newButton = QtGui.QPushButton('{d}'.format(d=day)) newButton.setSizePolicy( QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) # Highlight today's date in red if day == now.day and ( selected_date is None or (current_date.month == now.month and current_date.year == now.year)): newButton.setStyleSheet(stylesheet.TodayStyle) else: newButton.setStyleSheet( stylesheet.NormalMonthDayStyle) # newButton.setStyleSheet("QPushButton{border:none}") # newButton.clicked.connect(self.invoke_action) self.gridLayout.addWidget(newButton, row, column) self.dayBoxList.append(newButton)
import calendar m, d, y =map(int, raw_input().strip().split()) print calendar.day_name[calendar.weekday(y, m, d)].upper()
# # Sample Input # 08 05 2015 # # Sample Output # WEDNESDAY # # Explanation # The day on August 5th 2015 was WEDNESDAY. # ####################################################################################################################### import calendar sare = list(map(int, input().split(' '))) golmal = calendar.weekday(sare[2], sare[0], sare[1]) def apnaDay(x): return { 0: 'MONDAY', 1: 'TUESDAY', 2: 'WEDNESDAY', 3: 'THURSDAY', 4: 'FRIDAY', 5: 'SATURDAY', 6: 'SUNDAY' }.get(x) print(apnaDay(golmal))
import calendar, datetime, time print(calendar.weekheader(3)) # commment in python print(calendar.firstweekday()) print(calendar.month(2021, 4, 3)) #the last paremtr is the length of the month print(calendar.calendar(2021)) weekday = calendar.weekday(2000, 4, 9) print(weekday) isLeap = calendar.isleap(2020) print(isLeap) notleap = -1 if (isLeap): print("this year is leap year")
import calendar print(calendar.weekheader(3)) print() print(calendar.calendar(2050)) day_of_the_week = calendar.weekday(2050, 4, 21) print(day_of_the_week) is_leap = calendar.isleap(2024) print(is_leap) how_many_leap_days = calendar.leapdays(2000, 2021) print(how_many_leap_days)
4: "Abril", 5: "Mayo", 6: "Junio", 7: "Julio", 8: "Agosto", 9: "Septiembre", 10: "Octubre", 11: "Noviembre", 12: "Diciembre" } for vuelta in mi_rango(1, 12, 1): # da la totalidad de días que tiene ese mes en ese año fin_dias_mes = calendar.monthrange(anyo, mes)[1] #~ da el día de la semana que empieza el mes de lunes a domingo en 1 - 7 inicio_dia_semana = (calendar.weekday(anyo, mes, 1)) + 1 print meses[mes] for fila in mi_rango(1, 7, 1): for columna in mi_rango(1, 7, 1): if (fila == 1): if columna == 1: print "L ", if columna == 2: print "M ", if columna == 3: print "X ", if columna == 4: print "J ", if columna == 5:
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Nov 7 15:27:06 2019 numpy calendar @author: yoko """ import calendar #print(calendar.TextCalendar(firstweekday=6).formatyear(2109)) weekday=["MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY"] m,d,y = input().strip().split(' ') print(weekday[calendar.weekday(int(y),int(m),int(d))])
# Enter your code here. Read input from STDIN. Print output to STDOUT import calendar #calendar.Calendar(calendar.SUNDAY) user_input = input().split() month = int(user_input[0]) day = int(user_input[1]) year = int(user_input[2]) c = calendar.weekday(year, month, day) if c == 0: print("MONDAY") elif c == 1: print("TUESDAY") elif c == 2: print("WEDNESDAY") elif c == 3: print("THURSDAY") elif c == 4: print("FRIDAY") elif c == 5: print("SATURDAY") elif c == 6: print("SUNDAY")
def get_rh_date_and_day(hebrew_date, lenght, lang): # определяем число дней в месяце: month_days = dates.HebrewDate._month_length(hebrew_date[0], hebrew_date[1]) # определяем дату последнего дня месяца last_month_day = dates.HebrewDate(hebrew_date[0], hebrew_date[1], month_days ).to_greg().tuple() # определяем длинну рош ходеша if lenght == 2: # проверка на случай если два дня РХ в разных месяцах гр. календаря first_day = last_month_day[2] month_length = calendar.monthrange(last_month_day[0], last_month_day[1] )[1] if first_day == month_length: if last_month_day[1] == 12: # проверка на случай если это декабрь if lang == 'Русский': rh_days = '31 декабря {} года и 1 января {} года'.format( last_month_day[0], last_month_day[0] + 1 ) elif lang == 'English': rh_days = '31 December {} and 1 January {}'.format( last_month_day[0], last_month_day[0] + 1 ) # определяем день недели day_of_week_id = calendar.weekday( last_month_day[0], 12, 31 ) if lang == 'Русский': day_of_week = '{}-{}'.format( data.days_r[day_of_week_id], data.days_r[day_of_week_id + 1] ) elif lang == 'English': day_of_week = '{}-{}'.format( data.days_e[day_of_week_id], data.days_e[day_of_week_id + 1] ) else: if lang == 'Русский': rh_days = '{} и 1 {} и {} {} года'.format( first_day, data.gr_months_index[last_month_day[1]], data.gr_months_index[last_month_day[1] + 1], last_month_day[0] ) elif lang == 'English': rh_days = '{} and 1 {} and {} {}'.format( first_day, data.gr_months_index_en[last_month_day[1]], data.gr_months_index_en[last_month_day[1] + 1], last_month_day[0] ) # определяем день недели day_of_week_id = calendar.weekday( last_month_day[0], last_month_day[1], first_day ) if lang == 'Русский': day_of_week = '{}-{}'.format( data.days_r[day_of_week_id], data.days_r[day_of_week_id + 1] ) elif lang == 'English': day_of_week = '{}-{}'.format( data.days_e[day_of_week_id], data.days_e[day_of_week_id + 1] ) else: if lang == 'Русский': rh_days = '{} и {} {} {} года'.format( first_day, first_day + 1, data.gr_months_index[last_month_day[1]], last_month_day[0] ) elif lang == 'English': rh_days = '{} and {} {} {}'.format( first_day, first_day + 1, data.gr_months_index_en[last_month_day[1]], last_month_day[0] ) # определяем день недели day_of_week_id = calendar.weekday( last_month_day[0], last_month_day[1], first_day ) if lang == 'Русский': day_of_week = '{}-{}'.format( data.days_r[day_of_week_id], data.days_r[day_of_week_id + 1] ) elif lang == 'English': day_of_week = '{}-{}'.format( data.days_e[day_of_week_id], data.days_e[day_of_week_id + 1] ) else: # проверка на то, является ли число перед рх последним днем гр месяца month_length = calendar.monthrange( last_month_day[0], last_month_day[1] )[1] if last_month_day[2] == month_length: # проверка, является ли это декабрь if last_month_day[1] == 12: if lang == 'Русский': rh_days = '1 января {} года'.format(last_month_day[0] + 1) elif lang == 'English': rh_days = '1 January {}'.format(last_month_day[0] + 1) # определяем день недели day_of_week_id = calendar.weekday( last_month_day[0] + 1, 1, 1 ) if lang == 'Русский': day_of_week = data.days_r[day_of_week_id] elif lang == 'English': day_of_week = data.days_e[day_of_week_id] else: if lang == 'Русский': rh_days = '1 {} {} года'.format( data.gr_months_index[last_month_day[1] + 1], last_month_day[0] ) elif lang == 'English': rh_days = '1 {} {}'.format( data.gr_months_index_en[last_month_day[1] + 1], last_month_day[0] ) # определяем день недели day_of_week_id = calendar.weekday( last_month_day[0], last_month_day[1] + 1, 1 ) if lang == 'Русский': day_of_week = data.days_r[day_of_week_id] elif lang == 'English': day_of_week = data.days_e[day_of_week_id] else: if lang == 'Русский': rh_days = '{} {} {} года'.format( last_month_day[2] + 1, data.gr_months_index[last_month_day[1]], last_month_day[0] ) elif lang == 'English': rh_days = '{} {} {}'.format( last_month_day[2] + 1, data.gr_months_index_en[last_month_day[1]], last_month_day[0] ) # определяем день недели day_of_week_id = calendar.weekday( last_month_day[0], last_month_day[1], last_month_day[2] + 1) if lang == 'Русский': day_of_week = data.days_r[day_of_week_id] elif lang == 'English': day_of_week = data.days_e[day_of_week_id] return '{}, {}'.format(rh_days, day_of_week)
print(calendar.weekheader( 4)) #brojka u zagradi govori koliko ce se slova ispisati od dana print() print( calendar.firstweekday() ) #dani u tjednu su označeni brojkama, Pon = 0, Uto = 1 ... Prvi dan u tjednu kod Pythona je ponedjeljak print() #ispisuje prazan redak print( calendar.month(2020, 5, (3)) ) #ispisuje mjesec svibanj 2020. godine, dani u tjednu pišu se s tri slova print() print(calendar.monthcalendar(2020, 5)) #ispisuje matricu 5. mjeseca 2020. godine print() print(calendar.calendar(2020)) #ispisuje sve mjesece i dane u 2020. godini print() dan_u_tjednu = calendar.weekday( 2020, 5, 13 ) #ispisuje broj dana, 13.5. 2020. je srijeda odnosno 2, jer pon krece sa 0 print(dan_u_tjednu) print() prijestupna = calendar.isleap(2020) #provjerava je li 2020. godina prijestupna print(prijestupna) print()
import calendar s = "08 05 2015" deets = s.split() print(calendar.weekday(s[2], s[0], s[1]))
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ import calendar days = [ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" ] year = int(input("Years->")) mon = int(input("Month->")) date = int(input("Date->")) print(days[calendar.weekday(year, mon, date)]) input("Press any key to continue...")
import calendar import datetime import time print(calendar.weekheader(1)) print(calendar.weekheader(2)) print(calendar.weekheader(3)) print(calendar.weekheader(4)) print(calendar.weekheader(6)) print() # index of first weekday i.e. monday is 0 print(calendar.firstweekday()) print(calendar.month(2021, 3)) print(calendar.monthcalendar(2021, 3)) print(calendar.calendar(2021)) week_day = calendar.weekday(2021, 3, 4) print(week_day) is_leap = calendar.isleap(2020) print(is_leap) how_many_leap_days = calendar.leapdays(2020, 2050) print(how_many_leap_days)
def method1(self): return type(self) def method2(self): return self.__class__.__name__ def method3(self): return type(self)(self.whoareyou()) mani = human('mani') print(mani.method1()) print(mani.method2()) print(mani.method3()) import calendar print(calendar.weekday(2019, 7, 1)) c = calendar.Calendar(firstweekday=calendar.SUNDAY) year = 2019 month = 10 monthcal = c.monthdatescalendar(year, month) print(monthcal) second_tuesday = [ day for week in monthcal for day in week if day.weekday() == calendar.TUESDAY and day.month == month ][2] print(second_tuesday)
import calendar day = { 0: 'MONDAY', 1: 'TUESDAY', 2: 'WEDNESDAY', 3: 'THURSDAY', 4: 'FRIDAY', 5: 'SATURDAY', 6: 'SUNDAY' } m, d, y = map(int, raw_input().split()) print day[calendar.weekday(y, m, d)]
print(calendar.calendar(2018, 1, 3, 10)) #syntax year,width,column space, number of lines #output: calendar print(calendar.firstweekday()) #output: 0 print(calendar.isleap(2018)) #output: False print(calendar.leapdays(2010, 2018)) #output: 2 #number of leaf days between two years print(calendar.month(2018, 12, 1, 1)) #syntax year,month,width, number of lines #output: print given month print(calendar.monthcalendar(2018, 12)) #output: [[0, 0, 0, 0, 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, 0, 0, 0]] #list of integers print(calendar.monthrange(2018, 12)) # returns two integer 1st result is 1st day of given month and 2nd result is number of days in given month print(calendar.weekday(2018, 12, 17)) #output: returns the weekday code for given data 0 as Monday and 6 as Sunday print(calendar.prcal(2018)) #ouput: print calendar of given year with autofit
def calculate(client_list, hero_num, weekday_hrs, start_year, start_month, start_day, end_year, end_month, end_day): # for example # [43, 2, [[2019, 6, 20], [2019, 7, 23]]] total_weekdays, month_num, weekdays_month_plan = get_weekdays_num_month( start_year, start_month, start_day, end_year, end_month, end_day) # fixed, during the time scaled scale_factor, scaled_client_list = get_scaled_client_list( client_list, month_num, total_weekdays, hero_num, weekday_hrs) # detailed_allocation_now_month = [] # this is the merged plan final_final_allocation_list = [] relation_set_list = [] for i in range(hero_num): sub_set = OrderedSet() relation_set_list.append(sub_set) # every_month_details such as [2019, 7, 23] for every_month_details in weekdays_month_plan: now_year = every_month_details[0] now_month = every_month_details[1] day_num_month = every_month_details[2] # scaled and trimmed and trimed final_client_list_now_month = get_final_client_list_now_month( scaled_client_list, hero_num, day_num_month, weekday_hrs) print("year: {}".format(now_year)) print("month: {}".format(now_month)) print("\n scaled and trimed client list in {} this month is : {}\n". format(every_month_details, final_client_list_now_month)) # roughly allocation each month work_plan_now_month = get_total_work_plan(final_client_list_now_month, hero_num, day_num_month, weekday_hrs) # print("\n roughly work plan this month is:\n {}\n".format(work_plan_now_month)) for i in range(hero_num): hero_name = work_plan_now_month[i][0] relation_set_list[i].add(hero_name) client_num = len(work_plan_now_month[i]) - 1 if client_num <= 0: continue for client_id in range(client_num): relation_set_list[i].add(work_plan_now_month[i][client_id + 1][1]) # detailed allocation each month detailed_allocation_now_month = get_full_allocation_list( work_plan_now_month, weekday_hrs) # for each month add blank if it's boring days back_added_allocation_list = add_back_boring_days( detailed_allocation_now_month, day_num_month) print("detailed allocation this month is:\n {}\n".format( back_added_allocation_list)) final_final_allocation_list.append(back_added_allocation_list) # print(work_plan_now_month) print("----------------------------\n") final_relation_list = [] for hero_id in range(hero_num): sub_list = [] current_sub_set = relation_set_list[hero_id] for ele in current_sub_set: sub_list.append(ele) final_relation_list.append(sub_list) print("\nfinal relation list is: \n") print(final_relation_list) print("\n most complete allocation plan is : \n") print(final_final_allocation_list) first_month_allocation_list = final_final_allocation_list[0] if month_num > 1: # in every month for month_id in range(1, month_num): now_month_allocation_list = final_final_allocation_list[month_id] for hero_id in range(len(now_month_allocation_list)): total_allocation_days = len(now_month_allocation_list[hero_id]) for each_allocation_id in range(1, total_allocation_days): first_month_allocation_list[hero_id].append( now_month_allocation_list[hero_id][each_allocation_id]) # day_id from 0 - 6 means Monday - Sunday # test_day_id = calendar.weekday(start_year, start_month, start_day) # print("tested date id is :{}\n".format(test_day_id)) first_day_id = calendar.weekday(start_year, start_month, start_day) weekday_calendar = get_weekday_calendar(start_year, start_month, start_day, end_year, end_month, end_day) extreme_final_list = add_front_start_date(first_day_id, first_month_allocation_list) print("\n extreme_final_list is :\n") print(extreme_final_list) return weekday_calendar, scale_factor, extreme_final_list, final_relation_list
import calendar if __name__ == '__main__': date = input().split() days = list(calendar.day_name) print(days[calendar.weekday(int(date[2]), int(date[0]), int(date[1]))].upper())