def generateBDay(): year = random.randint(1940,2003) month = random.randint(1,12) dates = calendar.Calendar().itermonthdates(year, month) d = datetime.datetime.strptime(str(random.choice([date for date in dates if date.month == month])), '%Y-%m-%d') return str(d.strftime('%m/%d/%Y'))
async def rDaily(self): # Calculate Kickoff Date # First Staturday of January # Excluding If New Years is on Friday or Saturday, then following Saturday if self.kickoffDate == None: c = calendar.Calendar() for date in c.itermonthdates(datetime.today().date().year, 1): if date.day == 1 or date.day == 2: #If it is the first or second day of the month skip continue if date.weekday() == 5: #If DOW is Sat self.kickoffDate = date break # Week 1 = Kickoff + 6 Weeks Week1_START = kickoffDate + datetime.timedelta(weeks=6) Week1_END = Week1_START + datetime.timedelta(days=1) # Week 2 = Kickoff + 7 Weeks Week2_START = kickoffDate + datetime.timedelta(weeks=7) Week2_END = Week2_START + datetime.timedelta(days=1) # Week 3 = Kickoff + 8 Weeks Week3_START = kickoffDate + datetime.timedelta(weeks=8) Week3_END = Week3_START + datetime.timedelta(days=1) # Week 4 = Kickoff + 9 Weeks Week4_START = kickoffDate + datetime.timedelta(weeks=9) Week4_END = Week4_START + datetime.timedelta(days=1) # Week 5 = Kickoff + 10 Weeks Week5_START = kickoffDate + datetime.timedelta(weeks=10) Week5_END = Week5_START + datetime.timedelta(days=1) #DCMP #Week 6 = 11 Weeks Week6_START = kickoffDate + datetime.timedelta( weeks=11) - datetime.timedelta(days=3) Week6_END = kickoffDate + datetime.timedelta(weeks=11) #Week 7 = 12 Weeks Week7_START = kickoffDate + datetime.timedelta( weeks=12) - datetime.timedelta(days=3) Week7_END = kickoffDate + datetime.timedelta(weeks=12) #Week 8 = Worlds #week 9 = Worlds today = datetime.today().date() if today >= Week1_START and today <= Week1_END: # It is week 1! self.FIRSTInspiresHTTPAPI.update_AllDistrictEvents( districtCode="CHS" ) #Since it is week 1 sync all events from HQ self.FIRSTInspiresHTTPAPI.update_TodaysDistrictEvents( districtCode="CHS") self.rStartEventDay # Start the routines for the day elif today >= Week2_START and today <= Week2_END: # It is week 2! self.FIRSTInspiresHTTPAPI.update_TodaysDistrictEvents( districtCode="CHS") self.rStartEventDay # Start the routines for the day elif today >= Week3_START and today <= Week3_END: # It is week 3! self.FIRSTInspiresHTTPAPI.update_TodaysDistrictEvents( districtCode="CHS") self.rStartEventDay # Start the routines for the day elif today >= Week4_START and today <= Week4_END: # It is week 4! self.FIRSTInspiresHTTPAPI.update_TodaysDistrictEvents( districtCode="CHS") self.rStartEventDay # Start the routines for the day elif today >= Week5_START and today <= Week5_END: # It is week 5! #We do not normally have week 5 events but this will be a placeholder self.FIRSTInspiresHTTPAPI.update_TodaysDistrictEvents( districtCode="CHS") #self.rStartEventDay # Start the routines for the day elif today >= Week6_START and today <= Week6_END: # It is week 6 (DCMP 1)! self.FIRSTInspiresHTTPAPI.update_TodaysDistrictEvents( districtCode="CHS") self.rStartEventDay # Start the routines for the day elif today >= Week7_START and today <= Week7_END: # It is week 7 (DCMP 2)! self.FIRSTInspiresHTTPAPI.update_TodaysDistrictEvents( districtCode="CHS") self.rStartEventDay # Start the routines for the day else: #Disable all routines! self.fStopEventDay
def read_standardized_fields(raw_crashes, fields, opt_fields, start_year=None, end_year=None): crashes = {} for i, crash in enumerate(raw_crashes): if i % 10000 == 0: print(i) # skip any crashes that don't have coordinates if crash[fields["latitude"]] == "" or crash[fields["longitude"]] == "": continue # construct crash date based on config settings, skipping any crashes without date if fields["date_complete"]: if not crash[fields["date_complete"]]: continue else: crash_date = crash[fields["date_complete"]] elif fields["date_year"] and fields["date_month"]: if fields["date_day"]: crash_date = str(crash[fields["date_year"]]) + "-" + str(crash[ fields["date_month"]]) + "-" + crash[fields["date_day"]] # some cities do not supply a day of month for crashes, randomize if so else: available_dates = calendar.Calendar().itermonthdates( crash[fields["date_year"]], crash[fields["date_month"]]) crash_date = str( random.choice([ date for date in available_dates if date.month == crash[fields["date_month"]] ])) # skip any crashes that don't have a date else: continue crash_time = None if fields["time"]: crash_time = crash[fields["time"]] if fields["time_format"]: crash_date_time = parse_date(crash_date, crash_time, fields["time_format"]) else: crash_date_time = parse_date(crash_date, crash_time) # Skip crashes where date can't be parsed if not crash_date_time: continue # Drop crashes that occur outside of the range, if specified crash_year = date_parser.parse(crash_date_time).year if ((start_year is not None and crash_year < start_year) or (end_year is not None and crash_year > (end_year - 1))): continue formatted_crash = OrderedDict([ ("id", crash[fields["id"]]), ("dateOccurred", crash_date_time), ("location", OrderedDict([("latitude", float(crash[fields["latitude"]])), ("longitude", float(crash[fields["longitude"]]))])) ]) formatted_crash = add_city_specific_fields(crash, formatted_crash, opt_fields) crashes[formatted_crash["id"]] = formatted_crash return crashes
# All Rights Reserved # # Permission to use, copy, modify, and distribute this software and # its documentation for any purpose and without fee is hereby # granted, provided that the above copyright notice appear in all # copies and that both that copyright notice and this permission # notice appear in supporting documentation, and that the name of Doug # Hellmann not be used in advertising or publicity pertaining to # distribution of the software without specific, written prior # permission. # # DOUG HELLMANN DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, # INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN # NO EVENT SHALL DOUG HELLMANN BE LIABLE FOR ANY SPECIAL, INDIRECT OR # CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS # OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, # NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN # CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # """Show the yeardays2calendar return value. """ __module_id__ = "$Id$" #end_pymotw_header import calendar import pprint pprint.pprint(calendar.Calendar(calendar.SUNDAY).yeardays2calendar(2007, 2))
k_minmax = 12.0 k_step = 0.5 FACTOR = 64 sheet_name = [SHEET, 'under_fut'] header = 0 index_col = 0 skiprows = range(1, 13) data = pd.read_excel(filename, sheet_name=sheet_name, index_col=index_col, header=header, skiprows=skiprows) ty = data[SHEET].loc[start_date:end_date] ty.index = pd.to_datetime(ty.index) under_fut = data['under_fut'] #fill in the calendar of the expiry dates in Python c = calendar.Calendar(firstweekday=calendar.SATURDAY) s_exp_dt = pd.Series(index=under_fut.index, name='OPT_EXP_DT') for row in under_fut.itertuples(): contract = row.Index del_dt = row.FUT_DLV_DT_FIRST monthcal = c.monthdatescalendar(del_dt.year, del_dt.month-1) s_exp_dt.loc[contract] = monthcal[3][-1] #fourth friday of the month under_fut[s_exp_dt.name] = pd.to_datetime(s_exp_dt) ty = ty.merge(under_fut, right_on='OPT_EXP_DT',left_on='ticker',right_index=True) #assign the time to expiry ty['opt_tau_act365'] = (ty['OPT_EXP_DT'] - ty.index) / pd.Timedelta('365 days') ty.loc[ty['OPT_EXP_DT'] < ty.index, 'opt_tau_act365'] = 0 # do some data correction: remove some days where the vols are negative and unusable
def draw_cal(draw, screen_w, screen_h, day_view_divider, cal_divider, today): cal_padding = 6 header_h = 22 day_w = int((day_view_divider-cal_padding*2)/7) day_h = int((screen_h - cal_divider - header_h - cal_padding*2)/5) cal_bottom = screen_h - cal_padding cal_top = cal_bottom - day_h * 5 cal_left = cal_padding cal_right = cal_left + day_w * 7 header_top = cal_top - header_h #draw internal week lines for x in range(1,6): week_line = cal_bottom - day_h * x draw.line([(cal_left,week_line),(cal_right,week_line)], fill=0, width=1) #draw internal day lines for x in range(1,7): day_line = cal_left + day_w * x draw.line([(day_line, header_top),(day_line,cal_bottom)], fill=0, width=1) #draw external cal lines arc_d = 24 rounded_rect(draw, cal_left, header_top, cal_right, cal_bottom, arc_d, 0, 1) #calendar calculations this_month = calendar.Calendar(firstweekday=6) #returns calendar as list of date objects this_month_cal = this_month.monthdatescalendar(today.year,today.month) #calendar.setfirstweekday(calendar.SUNDAY) #cal_weekheader = calendar.weekheader(3) cal_weekheader = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'] font16 = ImageFont.truetype('./fonts/mononoki-Regular.ttf', 16) #draw day of week header/column titles header_w_offset = 8 header_h_offset = 6 for x in range(len(cal_weekheader)): font_offset = font16.getoffset(cal_weekheader[x]) draw.text((cal_left + header_w_offset - font_offset[0] + day_w * x, header_top + header_h_offset - font_offset[1]), cal_weekheader[x], font=font16) #draw all numbers on calendar num_w_offset = 8 #width offset from corner of day box num_h_offset = 8 #height offset from corner of day box marker_offset = 4 #offset from corner of day box marker_w = 26 #marker width marker_h = 18 #marker height m_arc_d = 12 #marker corner arc diameter for i in range(len(this_month_cal)): for j in range(len(this_month_cal[i])): font_offset = font16.getoffset(str(this_month_cal[i][j].day)) #dotted filled the days that are not part of this month if this_month_cal[i][j].month is not today.month: dotted_fill(draw, cal_left + day_w * j, cal_top + day_h * i, cal_left + day_w * (j + 1), cal_top + day_h * (i + 1), 2, 0) #hack to get rid of stray pixels in the bottom right corner if (i == len(this_month_cal)-1) and (j == len(this_month_cal[i])-1): draw.polygon([(cal_left + day_w * (j + 1), cal_top + day_h * (i + 1)), (cal_left + day_w * (j + 1) - arc_d/4, cal_top + day_h * (i + 1)), (cal_left + day_w * (j + 1), cal_top + day_h * (i + 1) - arc_d/4)], fill=255) #put marker on today's date if this_month_cal[i][j].day == today.day: marker_left = cal_left + marker_offset + day_w * j marker_top = cal_top + marker_offset + day_h * i marker_right = marker_left + marker_w marker_bottom = marker_top + marker_h filled_rounded_rect(draw, marker_left, marker_top, marker_right, marker_bottom, m_arc_d, 0) draw.text((cal_left + num_w_offset - font_offset[0] + day_w * j, cal_top + num_h_offset - font_offset[1] + day_h * i), str(this_month_cal[i][j].day), fill=255, font=font16) else: draw.text((cal_left + num_w_offset - font_offset[0] + day_w * j, cal_top + num_h_offset - font_offset[1] + day_h * i), str(this_month_cal[i][j].day), font=font16)
# built-in types (CH 5) a['ClassObjectType'] = _newclass # <type 'type'> a['ClassInstanceType'] = _newclass() # <type 'class'> a['SetType'] = _set = set() a['FrozenSetType'] = frozenset() # built-in exceptions (CH 6) a['ExceptionType'] = _exception = _function2()[0] # string services (CH 7) a['SREPatternType'] = _srepattern = re.compile('') # data types (CH 8) a['ArrayType'] = array.array("f") a['DequeType'] = collections.deque([0]) a['DefaultDictType'] = collections.defaultdict(_function, _dict) a['TZInfoType'] = datetime.tzinfo() a['DateTimeType'] = datetime.datetime.today() a['CalendarType'] = calendar.Calendar() if not PY3: a['SetsType'] = sets.Set() a['ImmutableSetType'] = sets.ImmutableSet() a['MutexType'] = mutex.mutex() # numeric and mathematical types (CH 9) a['DecimalType'] = decimal.Decimal(1) a['CountType'] = itertools.count(0) # data compression and archiving (CH 12) a['TarInfoType'] = tarfile.TarInfo() # generic operating system services (CH 15) a['LoggerType'] = logging.getLogger() a['FormatterType'] = logging.Formatter() # pickle ok a['FilterType'] = logging.Filter() # pickle ok a['LogRecordType'] = logging.makeLogRecord(_dict) # pickle ok a['OptionParserType'] = _oparser = optparse.OptionParser() # pickle ok
def _calendar(request, tipo=None, espaco=None, year=None, month=None, change=None): if not month and not year: today = datetime.today() year = today.year month = today.month """Listing of days in `month`.""" espaco, year, month = int(espaco), int(year), int(month) # apply next / previous change if change in ("next", "prev"): now, mdelta = date(year, month, 15), timedelta(days=31) if change == "next": mod = mdelta elif change == "prev": mod = -mdelta year, month = (now + mod).timetuple()[:2] # init variables cal = calendar.Calendar() month_days = cal.itermonthdays(year, month) nyear, nmonth, nday = time.localtime()[:3] lst = [[]] week = 0 for day in month_days: entries = current = False if day: if tipo == "e": entries = ReservaEquipamento.objects.filter(data__year=year, data__month=month, data__day=day, locavel=espaco, estado="A") elif tipo == "f": entries = ReservaEspacoFisico.objects.filter(data__year=year, data__month=month, data__day=day, locavel=espaco, estado="A") elif tipo == "s": entries = ReservaServico.objects.filter(data__year=year, data__month=month, data__day=day, locavel=espaco, estado="A") if day == nday and year == nyear and month == nmonth: current = True lst[week].append((day, entries, current)) if len(lst[week]) == 7: lst.append([]) week += 1 if (tipo == "e"): reservable = Equipamento.objects.get(id=espaco) elif tipo == 'f': reservable = EspacoFisico.objects.get(id=espaco) else: reservable = Servico.objects.get(id=espaco) return render( request, "agenda/calendar.html", dict(espaco=reservable, year=year, month=month, user=request.user, month_days=lst, mname=month_names[month - 1], tipo=tipo))
# set up command line args argparser = argparse.ArgumentParser( description="Generate Dynalist log entries for the specified month.") argparser.add_argument("-m", "--month", type=str, default="now", help="Month in ISO format: '2019-12'. " "If you give nothing, the current month is assumed.") args = argparser.parse_args() # input decisions month = args.month if month != "now": month += "-01" try: start = datetime.date.fromisoformat(month) except ValueError as error: print(error) exit() else: start = datetime.date.today().replace(day=1) # Generate dates for months days_of_month = reversed( list(calendar.Calendar().itermonthdates(start.year, start.month))) for day in days_of_month: if day.month != start.month: continue print(day.isoformat(), day.strftime("%a"))
month and render the calendar for that month of the current year. - If the user specifies two arguments, assume they passed in both the month and the year. Render the calendar for that month and year. - Otherwise, print a usage statement to the terminal indicating the format that your program expects arguments to be given. Then exit the program. """ import sys import calendar from datetime import datetime year = datetime.now().year month = datetime.now().month cal = calendar.Calendar().itermonthdates(year, month) def get_cal(month=month, year=year): months_dict = dict((v, k) for k, v in enumerate(calendar.month_abbr)) user_input = input( "Enter: month [year] ").split() if len(user_input) > 2: print("Try input again..") elif len(user_input) == 2: [month, year] = [user_input[0][:3].lower(), int(user_input[1])] for x in months_dict: if type(x) != int: if x.lower() == month: month = months_dict[x] print(calendar.TextCalendar(
def list_actions(request): can_add = request.user.has_perm('actions.add_action') if request.method == 'POST' and can_add: form = ActionForm(request.POST) if form.is_valid(): action = form.save() return redirect(action.get_absolute_url()) else: print(form.errors) return HttpResponseBadRequest # Attempt to read user and any url params: try: user, params = _get_action_request_params(request) except ValueError: return HttpResponseBadRequest() # Get all the actions for current user. actions = Action.objects.for_user(user) # Filter by tag tag_filter = params['tag'] if tag_filter: actions = actions.filter(tags__name=tag_filter) # Generate view for upcoming actions. future_actions = actions.filter(when__gte=now().date()) # Handle pagination range. num_pages = math.ceil(future_actions.count() / 10) # For pretty urls, page is 1 based. start_range = (params['page'] - 1) * 10 future_actions = future_actions[start_range:start_range+10] # Generate view for requested month's actions. current_date = params['date'] date_range = _make_date_range(current_date, include_future=False) current_actions = actions.filter(when__date__range=date_range) # Generate a mapping from day to list of actions for that day. actions_by_day = defaultdict(list) for action in current_actions: # Convert day to local day so actions land in the right day for current view. day = action.when.astimezone(tz.tzlocal()).date() actions_by_day[day].append(action) # Build a multi-level mapping of the current month in the form of: # month[week[day]] where each day has a list of events. cal_days = list(calendar.Calendar(firstweekday=6).itermonthdates(current_date.year, current_date.month)) month_actions = [] week_actions = [] today_tz = localtime().date() for daynum, mdate in enumerate(cal_days, 1): day_actions = list(map(_add_action_tag_color, actions_by_day[mdate])) day_data = { 'day': mdate, 'is_today': mdate == today_tz, 'actions': day_actions, 'is_cur_month': mdate.month == current_date.month } week_actions.append(day_data) if daynum % 7 == 0: month_actions.append(week_actions) week_actions = [] if week_actions: month_actions.append(week_actions) ctx = { 'future_actions' : future_actions, 'month_actions': month_actions, 'current_tag': tag_filter, 'current_date': current_date, 'next_month': current_date + timedelta(days=31), 'last_month': current_date + timedelta(days=-1), 'can_add': can_add, 'cur_page': params['page'], 'pages': range(1, num_pages+1), } if can_add: ctx['form'] = ActionForm() calendar_link = 'webcal://{}/action/ical/XR%20Mass%20Events'.format(request.get_host()) link_pars = {} if request.user.is_authenticated: link_pars['token'] = signing.Signer().sign(request.user.id) if tag_filter: link_pars['tag'] = tag_filter ctx['calendar_link'] = calendar_link + '?' + urlencode(link_pars) resp = render(request, 'list_actions.html', ctx) resp['Vary'] = 'Cookie' if request.user.is_authenticated: resp['Cache-Control'] = 'private' if actions: resp['Last-Modified'] = http_date(actions.last().when.timestamp()) return resp
def getDA(self): c = calendar.Calendar(firstweekday=calendar.SUNDAY) mcal = c.monthdatescalendar(self.given_date.year, self.given_date.month) da = {} counter = 0 da["CURR.DATE"] = self.given_date da["CURR.DAY"] = self.given_date.day da["CURR.DAYNAME"] = self.given_date.strftime("%A") da["CURR.DAYINDEX"] = self.given_date.weekday() da["CURR.WEEK"] = self.given_date.isocalendar()[1] da["CURR.WEEK_START"] = self.given_date - timedelta( days=self.given_date.weekday()) da["CURR.WEEK_END"] = self.given_date - timedelta( days=self.given_date.weekday()) + relativedelta(days=6) da["CURR.MONTHNAME"] = self.given_date.strftime("%B") da["CURR.MONTH"] = self.given_date.month da["CURR.MONTH_DAYS"] = calendar.monthrange(self.given_date.year, self.given_date.month)[1] da["CURR.MONTH_START"] = self.given_date.replace(day=1) da["CURR.MONTH_END"] = self.given_date.replace(day=calendar.monthrange( self.given_date.year, self.given_date.month)[1]) da["CURR.QUARTER"] = math.ceil(self.given_date.month / 3.) da["CURR.QUARTER_BEGIN"] = self.q[math.ceil(self.given_date.month / 3.)][0] da["CURR.QUARTER_END"] = self.q[math.ceil(self.given_date.month / 3.)][1] da["CURR.YEAR"] = self.given_date.year da["CURR.YEARS_DAYS"] = 366 if calendar.isleap( self.given_date.year) else 365 da["FIRST.MONDAY"] = [day for week in mcal for day in week if \ day.weekday() == calendar.MONDAY and \ day.month == self.given_date.month][0] da["FIRST.SUNDAY"] = [day for week in mcal for day in week if \ day.weekday() == calendar.SUNDAY and \ day.month == self.given_date.month][0] da["FIRST.MONDAY"] = [day for week in mcal for day in week if \ day.weekday() == calendar.MONDAY and \ day.month == self.given_date.month][0] da["FIRST.TUESDAY"] = [day for week in mcal for day in week if \ day.weekday() == calendar.TUESDAY and \ day.month == self.given_date.month][0] da["FIRST.WEDNESDAY"] = [day for week in mcal for day in week if \ day.weekday() == calendar.WEDNESDAY and \ day.month == self.given_date.month][0] da["FIRST.THURSDAY"] = [day for week in mcal for day in week if \ day.weekday() == calendar.THURSDAY and \ day.month == self.given_date.month][0] da["FIRST.FRIDAY"] = [day for week in mcal for day in week if \ day.weekday() == calendar.FRIDAY and \ day.month == self.given_date.month][0] da["FIRST.SATURDAY"] = [day for week in mcal for day in week if \ day.weekday() == calendar.SATURDAY and \ day.month == self.given_date.month][0] da["COUNT.SUNDAY"] = sum([counter+1 for day in c.itermonthdates(self.given_date.year, self.given_date.month) \ if day.weekday() == 6 and day.month == self.given_date.month]) da["COUNT.MONDAY"] = sum([counter + 1 for day in c.itermonthdates(self.given_date.year, self.given_date.month) \ if day.weekday() == 0 and day.month == self.given_date.month]) da["COUNT.TUESDAY"] = sum([counter + 1 for day in c.itermonthdates(self.given_date.year, self.given_date.month) \ if day.weekday() == 1 and day.month == self.given_date.month]) da["COUNT.WEDNESDAY"] = sum([counter + 1 for day in c.itermonthdates(self.given_date.year, self.given_date.month) \ if day.weekday() == 2 and day.month == self.given_date.month]) da["COUNT.THURSDAY"] = sum([counter + 1 for day in c.itermonthdates(self.given_date.year, self.given_date.month) \ if day.weekday() == 3 and day.month == self.given_date.month]) da["COUNT.FRIDAY"] = sum([counter + 1 for day in c.itermonthdates(self.given_date.year, self.given_date.month) \ if day.weekday() == 4 and day.month == self.given_date.month]) da["COUNT.SATURDAY"] = sum([counter + 1 for day in c.itermonthdates(self.given_date.year, self.given_date.month) \ if day.weekday() == 5 and day.month == self.given_date.month]) return da
class NYSEcalendar(object): """ The Board has determined that the Exchange will not be open for business on New Year's Day, Martin Luther King, Jr. Day, Washington's Birthday, Good Friday, Memorial Day, Independence Day, Labor Day, Thanksgiving Day and Christmas Day. Martin Luther King, Jr. Day, Washington's Birthday and Memorial Day will be celebrated on the third Monday in January, the third Monday in February and the last Monday in May, respectively The Exchange Board has also determined that, when any holiday observed by the Exchange falls on a Saturday, the Exchange will not be open for business on the preceding Friday and when any holiday observed by the Exchange falls on a Sunday, the Exchange will not be open for business on the succeeding Monday, unless unusual business conditions exist, such as the ending of a monthly or the yearly accounting period. """ _cal = calendar.Calendar() @classmethod def _weekdays(cls, year, month, weekday): """ Filter datetime.dates in (year, month) for a given weekday. """ def weekdayTest(days): return (days[0] > 0) and (days[1] == weekday) return [datetime.date(year, month, day) \ for (day, wkday) in itertools.ifilter(weekdayTest, cls._cal.itermonthdays2(year, month))] @classmethod def mondays(cls, year, month): return cls._weekdays(year, month, weekday=0) @classmethod def thursdays(cls, year, month): return cls._weekdays(year, month, weekday=3) @classmethod def holidays(cls, year): hols = [datetime.date(year, 7, 4), # Independence Day datetime.date(year, 12, 25), # Christmas cls.mondays(year, 1)[2], # MLK Day findEaster(year) - datetime.timedelta(days=2), # Good Friday cls.mondays(year, 2)[2], # Washington's Birthday cls.mondays(year, 5)[-1], # Memorial Day cls.mondays(year, 9)[0], # Labor Day cls.thursdays(year, 11)[-1], # Thanksgiving ] newYearsDay = datetime.date(year, 1, 1) if newYearsDay.weekday() != 5: # If New Year's Day falls on a Saturday, then it would get moved # back to the preceding Friday, except that would be 12/31, which # is the close of the monthly and annual accounting cycle... so # in that case, the holiday just gets skipped instead. hols.append(newYearsDay) hols.sort() return hols
def streak(uid): session['uid'] = uid print "in streak function for user", uid user_data = UserActivity.query.filter_by(user_id=uid).order_by( UserActivity.id.desc()).first() daily_activity = user_data.daily_activity overall_activity = user_data.overall_activity for y in overall_activity: y.encode('UTF8') overall_activity = overall_activity[1:] overall_activity = overall_activity[:-1] overall_activity = overall_activity.split(", ") data_points = [ overall_activity[0], overall_activity[1], overall_activity[2] ] for x in daily_activity: x.encode('UTF8') daily_activity = daily_activity[2:] daily_activity = daily_activity[:-2] daily_activity = daily_activity.split("], [") daily_list = [] for y in daily_activity: y = y.split(", ") daily_list.append([y[0][1:-1], int(y[1])]) daily_list = sorted(daily_list, key=itemgetter(0)) n = ['', 0] rejects = [] for dt in daily_list: if dt[0] == n[0]: if dt[1] >= n[1]: rejects.append(n) else: rejects.append(dt) n = dt for x in daily_list: for y in rejects: if x == y: daily_list.remove(x) first_date = daily_list[0] first_date = first_date[0] initial_year = int(first_date[0:4]) initial_month = int(first_date[5:7]) cal = calendar.Calendar() coursecal = [] monday = [] tuesday = [] wednesday = [] thursday = [] friday = [] saturday = [] sunday = [] while initial_month <= 12: for x in cal.itermonthdays2(initial_year, initial_month): if int(x[0]) != 0: activity = 0 weekday = int(x[1]) for y in daily_list: if int(y[0][5:7]) == int(initial_month) and int( y[0][8:10]) == int(x[0]): activity = int(y[1]) eachday = [(str(initial_month) + "-" + str(x[0])), activity, weekday] coursecal.append(eachday) initial_month += 1 zeros = [] for x in coursecal: if int(x[1]) == 0: zeros.append(x) else: break for y in zeros: for x in coursecal: if y[0] == x[0] and y[1] == x[1]: coursecal.remove(x) todaysdate = datetime.datetime.utcnow() todaysdate = str(todaysdate) todaysmonth = int(todaysdate[5:7]) todaysday = int(todaysdate[8:10]) today = str(todaysmonth) + "-" + str(todaysday) # this is temporary please remove print "the real date is", today coursecalupdate = [] for x in coursecal: if today != x[0]: coursecalupdate.append(x) elif today == x[0]: coursecalupdate.append(x) break coursecal = coursecalupdate streak_data = [] for x in coursecal: streak_data.append(x[1]) streak = 0 allstreaks = [] for x in streak_data: if x > 0: streak += 1 else: allstreaks.append(streak) streak = 0 allstreaks.append(streak) threestreak = 0 fourstreak = 0 fivestreak = 0 sixstreak = 0 sevenstreak = 0 eightstreak = 0 ninestreak = 0 tenstreak = 0 for y in allstreaks: if y >= 3: threestreak += 1 if y >= 4: fourstreak += 1 if y >= 5: fivestreak += 1 if y >= 6: sixstreak += 1 if y >= 7: sevenstreak += 1 if y >= 8: eightstreak += 1 if y >= 9: ninestreak += 1 if y >= 10: tenstreak += 1 three_five_seven = [threestreak, fivestreak, sevenstreak] # longest streak longest = 0 for x in allstreaks: if x > longest: longest = x # current streak current = 1 if streak_data[len(streak_data) - 1] > 0: current += allstreaks[len(allstreaks) - 1] to_date = int(len(coursecal)) this_week = [] for n in range(1, 8): this_week.append(coursecal[to_date - n]) this_week_new = [] for x in this_week: if x[2] == 0: this_week_new.append(x) break else: this_week_new.append(x) this_week = this_week_new week_act = [] for x in this_week: week_act.insert(0, x[1]) for z in coursecal: if z[2] == 0: a = [z[0], z[1]] monday.append(a) if z[2] == 1: tuesday.append(z) a = [z[0], z[1]] if z[2] == 2: wednesday.append(z) a = [z[0], z[1]] if z[2] == 3: thursday.append(z) a = [z[0], z[1]] if z[2] == 4: friday.append(z) a = [z[0], z[1]] if z[2] == 5: saturday.append(z) a = [z[0], z[1]] if z[2] == 6: sunday.append(z) a = [z[0], z[1]] monday_act = 0 tuesday_act = 0 wednesday_act = 0 thursday_act = 0 friday_act = 0 saturday_act = 0 sunday_act = 0 for x in monday: monday_act += x[1] monday_act = float(monday_act) / float(len(monday)) monday_act = float(format(monday_act, '.2f')) for x in tuesday: tuesday_act += x[1] tuesday_act = float(tuesday_act) / float(len(tuesday)) tuesday_act = float(format(tuesday_act, '.2f')) for x in wednesday: wednesday_act += x[1] wednesday_act = float(wednesday_act) / float(len(wednesday)) wednesday_act = float(format(wednesday_act, '.2f')) for x in thursday: thursday_act += x[1] thursday_act = float(thursday_act) / float(len(thursday)) thursday_act = float(format(thursday_act, '.2f')) for x in friday: friday_act += x[1] friday_act = float(friday_act) / float(len(friday)) friday_act = float(format(friday_act, '.2f')) for x in saturday: saturday_act += x[1] saturday_act = float(saturday_act) / float(len(saturday)) saturday_act = float(format(saturday_act, '.2f')) for x in sunday: sunday_act += x[1] sunday_act = float(sunday_act) / float(len(sunday)) sunday_act = float(format(sunday_act, '.2f')) month_act = [ monday_act, tuesday_act, wednesday_act, thursday_act, friday_act, saturday_act, sunday_act ] new_month_act = [] return month_act, week_act, data_points, three_five_seven, longest, current
def weekly_menus(): # Creates a calendar object c = calendar.Calendar() cal = "" # Gets the names of all 12 months months = calendar.month_name # Gets todays date and time now = datetime.datetime.now() # Gets this year and assigns it to a variable year = now.year # Gets this month integer and assigns it to a variable month = now.month # Gets this months name based on this months integer month_name = months[month] if request.method == "POST": # Gets the forms entered year selected_year = int(request.form.get("year_select")) # Gets the forms entered month selected_month = int(request.form.get("month_select")) # Checks if the week_select input is set to the default value has_week = request.form.get("week_select") # If it is then return the whole weeks in the month as options if has_week == "no weeks": cal = c.monthdayscalendar(selected_year, selected_month) month_name = months[selected_month] # Get all the plans for the user to display on the page plans = list( # Ordered in decending date order mongo.db.weekly_plans.find().sort("week_commencing", -1)) # Get recipes recipes = list(mongo.db.recipes.find()) return render_template( "weekly_menus.html", cal=cal, year=selected_year, month=selected_month, month_name=month_name, plans=plans, recipes=recipes) # If the week has been selected create a new plan else: cal = c.monthdayscalendar(selected_year, selected_month) week = int(request.form.get("week_select")) days = cal[week] meals = [] year = str(request.form.get("year_select")) month = str(request.form.get("month_select")) # If the month integer is a single digit add a 0 before it if len(month) == 1: month = "0" + month # If the day integer is a single digit add a 0 before it day = str(days[0]) if len(day) == 1: day = "0" + day # Creates a data string with common number of digits for sorting date = year + month + day exists = mongo.db.weekly_plans.find_one({ "owner": session["wft_user"][0], "week_commencing": date }, "week_commencing") if not exists: recipes = list( mongo.db.recipes.find( {"shared_with": session["wft_user"][0]}, "_id")) for day in days: # thanks to machine learning mastery # for tips and advice on random and choice # https://machinelearningmastery.com/how-to-generate-random-numbers-in-python/ meal = choice(recipes) # append each choice to a list meals.append(meal) # Weekly plan object created weekly_plan = { "owner": session["wft_user"][0], "week_commencing": date, "year": year, "month": month, "days": days, "meals": meals } # Sends the object to MongoDB mongo.db.weekly_plans.insert_one(weekly_plan) # Lets the user know the object has been sent flash("Created New Menu") # Takes the user back to the recipes page to see their recipes return redirect(url_for("weekly_menus")) else: flash("Menu already exists. Choose another week.") return redirect(url_for("weekly_menus")) plans = list(mongo.db.weekly_plans.find().sort("week_commencing", -1)) recipes = list(mongo.db.recipes.find()) return render_template( "weekly_menus.html", year=year, month=month, month_name=month_name, plans=plans, recipes=recipes)
def __init__(self): DressMe.__init__(self) self.cal = calendar.Calendar(firstweekday=0) self.dress = [] self.calendar_date = []
################################################################# #Clase_fechas_Ej_026 print("Obtener calendario del mes actual (calendar.TextCalendar)") print("Se establece el lunes como primer día de la semana") calendario = calendar.TextCalendar(calendar.MONDAY) calendario.prmonth(año, mes) limpiar() ################################################################# print( "Obtener matriz con calendario de mes actual: (Calendar monthdayscalendar)" ) calendario = calendar.Calendar() for elemento in calendario.monthdayscalendar(año, mes): print(elemento) nuevo(26) ################################################################# #Clase_fechas_Ej_027 print("Obtener matriz de tuplas con calendario: (Calendar monthdays2calendar)") print( "El primer valor de cada par es el número de día del mes y el segundo valor se corresponde con el número de día de la semana: 0:lunes, 1:martes, 2:miércoles, etc." ) calendario = calendario.monthdays2calendar(año, mes) for elemento in calendario: print(elemento)
l = list() d = dict() l2 = list() address = "list.xls" conn = sqlite3.connect("personel") curser = conn.cursor() curser.execute('SELECT * FROM main') rows = curser.fetchall() for row in rows: d[row[2]] = row[3] today = str(jdatetime.date.today()) today_list = today.split('-') taqv = calendar.Calendar() month_list = taqv.monthdayscalendar(int(today_list[0]), int(today_list[1])) for i in range(0, len(month_list)): if int(today_list[2]) in month_list[i]: this_week = month_list[i] print('^^^^^^^^^^^^^^^^^^^^^^^^^^') print('Today date:', today) print('^^^^^^^^^^^^^^^^^^^^^^^^^^') for i in d: name = i date_list = d[i].split('/')
# importing libraries import calendar as c import time as t # Creates an instance of a calendar cal = c.Calendar() tCal = c.TextCalendar() hCal = c.HTMLCalendar() # Calendar # An object that returns all days for the month includes week before and after mon1 = cal.itermonthdates(2021, 3) # A list that returns all days for the month includes week before and after mon2 = cal.monthdatescalendar(2021, 3) # A list that returns all days for the year includes week before and after year1 = cal.yeardatescalendar(2021, 3) # Text calendar # month string tMonth = tCal.formatmonth(2021, 3) # print current month string tCal.prmonth(2021, 3) # year string tYear = tCal.formatyear(2021)
def test_yeardayscalendar(self): self.assertEqual(calendar.Calendar().yeardayscalendar(2004), result_2004_days)
# updates day nums for current month day_nums = 29 row = 31 while day_nums <= how_many_month_days: sheet.update_cell(row, 1, day_nums) row = row + 1 day_nums = day_nums + 1 print('Day numbers updated') # gets correct weekdays for month in list weekdays = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'] month_days = [] start_total = 0 end_total = 0 cal = calendar.Calendar(firstweekday=0) for day in cal.itermonthdays(current_year, current_month): if day == 0: start_total = start_total + 1 elif day == 1: break for day in cal.itermonthdays(current_year, current_month): if day > 0: end_total = end_total + 1 start_day = weekdays[start_total] # starts loop midweek on correct day day_num = 1 for each in weekdays[start_total:]:
def test_itermonthdates(self): # ensure itermonthdates doesn't overflow after datetime.MAXYEAR # see #15421 list(calendar.Calendar().itermonthdates(datetime.MAXYEAR, 12))
def list_actions(request): can_add = request.user.has_perm("actions.add_action") if request.method == "POST" and can_add: form = ActionForm(request.POST) if form.is_valid(): action = form.save() return redirect(action.get_absolute_url()) else: return HttpResponseBadRequest() # Attempt to read user and any url params: try: user, params = _get_action_request_params(request) except ValueError: return HttpResponseBadRequest() # Get all the actions for current user. actions = Action.objects.for_user(user) # Filter by tag tag_filter = params["tag"] if tag_filter: actions = actions.filter(tags__name=tag_filter) # Generate view for upcoming actions. today_tz = make_aware(datetime.combine(localtime().date(), datetime.min.time())) future_actions = actions.filter(when__gte=today_tz) # Handle pagination range. num_pages = math.ceil(future_actions.count() / 10) # For pretty urls, page is 1 based. start_range = (params["page"] - 1) * 10 future_actions = future_actions[start_range : start_range + 10] # Generate view for requested month's actions. current_date = params["date"] date_range = _make_date_range(current_date, include_future=False) current_actions = actions.filter(when__date__range=date_range) # Generate a mapping from day to list of actions for that day. actions_by_day = defaultdict(list) for action in current_actions: # Convert day to local day so actions land in the right day for current view. day = action.when.astimezone(tz.tzlocal()).date() actions_by_day[day].append(action) # Build a multi-level mapping of the current month in the form of: # month[week[day]] where each day has a list of events. cal_days = list( calendar.Calendar(firstweekday=6).itermonthdates( current_date.year, current_date.month ) ) month_actions = [] week_actions = [] for daynum, mdate in enumerate(cal_days, 1): # produce a list of actions for each day. day_actions = list(map(_add_action_tag_color, actions_by_day[mdate])) day_data = { "day": mdate, "is_today": mdate == today_tz, "actions": day_actions, "is_cur_month": mdate.month == current_date.month, } week_actions.append(day_data) if daynum % 7 == 0: month_actions.append(week_actions) week_actions = [] if week_actions: month_actions.append(week_actions) ctx = { "future_actions": future_actions, "month_actions": month_actions, "current_tag": tag_filter, "current_date": current_date, "next_month": current_date + timedelta(days=31), "last_month": current_date + timedelta(days=-1), "can_add": can_add, "cur_page": params["page"], "pages": range(1, num_pages + 1), } if can_add: ctx["form"] = ActionForm() calendar_link = "webcal://{}/action/ical/XR%20Mass%20Events".format( request.get_host() ) link_pars = {} if request.user.is_authenticated: link_pars["token"] = signing.Signer().sign(request.user.id) if tag_filter: link_pars["tag"] = tag_filter ctx["calendar_link"] = calendar_link + "?" + urlencode(link_pars) resp = render(request, "list_actions.html", ctx) resp["Vary"] = "Cookie" if request.user.is_authenticated: resp["Cache-Control"] = "private" if actions: resp["Last-Modified"] = http_date(actions.last().when.timestamp()) return resp
def main(token, queryid): # util.logToConsole(logging.DEBUG) report = 'report.xml' ib = IB() #ib.connect('127.0.0.1', 7497, clientId=1, readonly=True) # click.echo(util.df(ib.portfolio())) r = FlexReport() if (path.exists(report)): r.load(report) else: r.download(token, queryid) r.save(report) df = r.df('Trade') df['stock'] = df.apply( lambda row: row.symbol if row.assetCategory == 'STK' else row.underlyingSymbol, axis=1) df['shortLong'] = df.apply( lambda row: 'S' if row.buySell == 'SELL' and row.openCloseIndicator == 'O' or row.buySell == 'BUY' and row.openCloseIndicator == 'C' else 'L', axis=1) df['datetime_date'] = df.apply( lambda row: datetime.strptime(row.dateTime, '%Y-%m-%d %H:%M:%S'), axis=1) df['week'] = df.apply( lambda row: row.datetime_date.date().isocalendar()[1], axis=1) df['month'] = df.apply(lambda row: row.datetime_date.date().month, axis=1) c = calendar.Calendar(firstweekday=calendar.SUNDAY) def options_month(d): monthcal = c.monthdatescalendar(d.year, d.month) third_week = [ day for week in monthcal for day in week if day.weekday() == calendar.FRIDAY and day.month == d.month ][2] if d.day <= third_week.day + 1: return d.month else: return d.month + 1 df['options_month'] = df.apply( lambda row: options_month(row.datetime_date), axis=1) # df.to_excel("report.xlsx") # df1 = df[['accountId', 'currency', 'fxRateToBase', 'assetCategory', # 'symbol', 'description', 'conid', 'underlyingSymbol', 'multiplier', 'strike', 'expiry', 'putCall', 'dateTime', 'quantity', 'tradePrice', 'tradeMoney', 'proceeds', 'taxes', #'ibCommission', 'ibCommissionCurrency', 'netCash', 'closePrice', 'openCloseIndicator', 'notes', 'cost', 'fifoPnlRealized', 'mtmPnl', 'buySell', 'Week', 'Month']].copy() # click.echo(df1) df_closed = df[(df['openCloseIndicator'] == 'C')] df_stock = df[(df['assetCategory'] == 'STK') & (df['openCloseIndicator'] == 'C')] df_options = df[(df['assetCategory'] == 'OPT') & (df['openCloseIndicator'] == 'C')] # click.echo(pd.pivot_table( # df_options, index=["underlyingSymbol"], columns=['options_month', 'week'], values=["fifoPnlRealized"], fill_value=0, aggfunc=[np.sum], margins=True, margins_name='Total')) click.echo( pd.pivot_table(df_closed, index=['assetCategory', 'shortLong', 'stock'], columns=['options_month', 'week'], values=["fifoPnlRealized"], fill_value=0, aggfunc=[np.sum], margins=True, margins_name='Total')) ib.disconnect()
#!/usr/bin/env python3 import calendar cal = calendar.Calendar(calendar.SUNDAY) cal_data = cal.yeardays2calendar(2017, 3) print("Length : {}".format(len(cal_data))) top_months = cal_data[0] print("Length of top_months: {}".format(len(top_months))) first_month = top_months[0] print("Length of first_month: {}".format(len(first_month))) #print("First month")
使用 TextCalendar 类的 formatyear() 返回整年的3列的日历以多行字符串的形式。 calendar.timegm(tuple) 一个不相关但很好用的函数,它接受一个时间元组例如 time 模块中的 gmtime() 函数的返回并返回相应的 Unix 时间戳值,假定 1970 年开始计数, POSIX 编码。实际上, time.gmtime() 和 timegm() 是彼此相反的。 """ for i in calendar.day_name: print(i) for i in calendar.day_abbr: print(i) for i in calendar.month_name: print(i) for i in calendar.month_abbr: print(i) print("------------------") # class calendar.Calendar c = calendar.Calendar(0) for i in c.iterweekdays(): print(i) # c = calendar.Calendar(6) 是不一样的结果 for i in c.itermonthdates(2020, 5): print(i) # 返回的日期为当月每一天的日期对应的天数。对于不在当月的日期,显示为 0。 for i in c.itermonthdays(2020, 5): print(i) # 迭代器中的元素为一个由日期和代表星期几的数字组成的的元组。 for i in c.itermonthdays2(2020, 5): print(i) # 迭代器的元素为一个由年,月,日组成的元组。
def format_month(self, month: calendar.Calendar().monthdatescalendar, activities: list[PresentationActivity]): m = [] for week in month: m.append(self.format_week(week, activities)) return m
}, 'mid': { 0: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"], 6: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] }, 'long': { 0: ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"], 6: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] } } first_day = int(PROPS.get('firstDayOfWeek', 6)) day_format = PROPS.get('dayOfWeekFormat', 'mid') days_labels = fmt[day_format][first_day] my_cal = calendar.Calendar(first_day) # first day is Sunday = 6, Monday = 0 today = dt.datetime.today() cal = my_cal.monthdatescalendar(today.year, today.month) try: height = int(PROPS.get('customSizeHeight', 200)) / int(plt.rcParams['savefig.dpi']) except ValueError: height = 2 try: width = int(PROPS.get('customSizeWidth', 500)) / int(plt.rcParams['savefig.dpi']) except ValueError: width = 5 fig = plt.figure(figsize=(width, height)) ax = fig.add_subplot(111)
#inkyphat.set_rotation(180) # Load our sprite sheet and prepare a mask text = Image.open("resources/calendar.png") text_mask = inkyphat.create_mask(text, [inkyphat.WHITE]) # Note: The mask determines which pixels from our sprite sheet we want # to actually use when calling inkyphat.paste # which uses PIL's Image.paste() method, # See: http://pillow.readthedocs.io/en/3.1.x/reference/Image.html?highlight=paste#PIL.Image.Image.paste # Load our backdrop image inkyphat.set_image("resources/empty-backdrop.png") # Grab the current date, and prepare our calendar cal = calendar.Calendar() now = datetime.datetime.now() dates = cal.monthdatescalendar(now.year, now.month) col_w = 20 col_h = 13 cols = 7 rows = len(dates) + 1 cal_w = 1 + ((col_w + 1) * cols) cal_h = 1 + ((col_h + 1) * rows) cal_x = inkyphat.WIDTH - cal_w - 2 cal_y = 2
def get_weekdays(year, month): cobj = calendar.Calendar(calendar.SUNDAY) return cobj.monthdayscalendar(year, month)