Python calendar.weekday() Examples
The following are 22
code examples of calendar.weekday().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
calendar
, or try the search function
.
Example #1
Source File: test_monthday_setbuilder.py From aws-ops-automator with Apache License 2.0 | 6 votes |
def test_W_wildcard(self): years = [2016, 2017] # leap and normal year for year in years: for month in range(1, 13): _, days = calendar.monthrange(year, month) for day in range(1, days): weekday = calendar.weekday(year, month, day) result = day if weekday == 5: result = day - 1 if day > 1 else day + 2 elif weekday == 6: result = day + 1 if day < days else day - 2 self.assertEqual(MonthdaySetBuilder(year, month).build(str(day) + "W"), {result})
Example #2
Source File: executor.py From CUP with Apache License 2.0 | 6 votes |
def next_monthday_weekday(cls, tmp_dict, timer_params): """ set next monthday && weekday """ plus = 1 while True: tmp_dict['monthday'] += plus if plus == 0: plus = 1 if all([ tmp_dict['monthday'] in timer_params['monthday'], cls.check_monthday_weekday(tmp_dict, timer_params) ]): tmp_dict['hour'] = timer_params['hour'][0] tmp_dict['minute'] = timer_params['hour'][0] break else: if tmp_dict['monthday'] > 31: cls.next_month(tmp_dict, timer_params) plus = 0
Example #3
Source File: hs-schedule.py From hacker-scripts with GNU General Public License v3.0 | 6 votes |
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))
Example #4
Source File: export.py From script.module.clouddrive.common with GNU General Public License v3.0 | 6 votes |
def process_schedules(self, export_map, now, startup=False): Logger.debug('now: %s, startup: %s' % (Utils.str(now), Utils.str(startup))) export_list = [] if startup: export_list.extend(Utils.get_safe_value(export_map, self._startup_type, [])) else: at = '%02d:%02d' % (now.hour, now.minute,) Logger.debug('at: %s' % Utils.str(at)) daily_list = Utils.get_safe_value(export_map, Utils.str(ExportScheduleDialog._daily_type) + at, []) export_list.extend(daily_list) Logger.debug('daily_list: %s' % Utils.str(daily_list)) weekday = now.weekday() + 11 weekday_list = Utils.get_safe_value(export_map, Utils.str(weekday) + at, []) export_list.extend(weekday_list) Logger.debug('weekday_list: %s' % Utils.str(weekday_list)) Logger.debug('export_list: %s' % Utils.str(export_list) ) for export in export_list: self.run_export(export)
Example #5
Source File: cron.py From abusehelper with MIT License | 5 votes |
def __init__(self, *args, **keys): self._spec = {} max_priority = min(x.time_tuple_index for x in self._units.values()) for key, arg in dict(*args, **keys).iteritems(): if key not in self._units: raise TypeError("unexpected unit {0!r}".format(key)) unit = self._units[key] max_priority = max(max_priority, unit.time_tuple_index) rangeobj = self._coerce(arg) self._spec[key] = unit.resolve(rangeobj) for key, unit in self._units.iteritems(): if key in self._spec: continue if max_priority >= unit.time_tuple_index: self._spec[key] = unit.resolve(any()) else: self._spec[key] = unit.resolve(value(unit.min)) # Special case: If both day or weekday is limited, then use OR instead of AND. if self._is_any("day"): self._spec["day"] = self._units["day"].resolve(empty()) elif self._is_any("weekday"): self._spec["weekday"] = self._units["weekday"].resolve(empty()) self._spec["day"] = _ResolvedOr(self._spec.pop("day"), self._spec.pop("weekday"))
Example #6
Source File: executor.py From CUP with Apache License 2.0 | 5 votes |
def check_monthday_weekday(cls, tmp_dict, timer_params): """check if monthday / weekday valid""" try: day = calendar.weekday( tmp_dict['year'], tmp_dict['month'], tmp_dict['monthday'] ) + 1 # e.g. invalid date, 4.31 except ValueError: return False if day in timer_params['weekday']: return True else: return False
Example #7
Source File: executor.py From CUP with Apache License 2.0 | 5 votes |
def next_month(cls, tmp_dict, timer_params): """ set tmp_dict to next valid date, specifically month :param tmp_dict: { 'year': xxxx, 'month': xxxx, 'monthday': xxxx, 'weekday': xxxx, 'hour': xxxx, 'minute': xxxx } :param timer_params: valid timer dict, same to self._timer_params """ while True: tmp_dict['month'] += 1 if tmp_dict['month'] in timer_params['month']: break else: if tmp_dict['month'] > 12: tmp_dict['month'] = timer_params['month'][0] tmp_dict['year'] += 1 break monthday = [x for x in range( 1, calendar.monthrange(tmp_dict['year'], tmp_dict['month'])[1] + 1 ) \ if x in timer_params['monthday'] ] tmp_dict['monthday'] = monthday[0] tmp_dict['hour'] = timer_params['hour'][0] tmp_dict['minute'] = timer_params['minute'][0] tmp_dict['weekday'] = calendar.weekday( tmp_dict['year'], tmp_dict['month'], tmp_dict['monthday'] ) + 1 timer_params['monthday'] = monthday
Example #8
Source File: rollover.py From backtrader with GNU General Public License v3.0 | 5 votes |
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)
Example #9
Source File: DateTime.py From Pair-Trading-Reinforcement-Learning with MIT License | 5 votes |
def get_dates_weekday(start_date, end_date): dt = end_date - start_date dates = [] for i in range(dt.days + 1): date = start_date + datetime.timedelta(i) if calendar.weekday(date.year, date.month, date.day) < 5: dates.append(date) return dates
Example #10
Source File: holidays.py From convertdate with MIT License | 5 votes |
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)
Example #11
Source File: utils.py From convertdate with MIT License | 5 votes |
def nth_day_of_month(n, weekday, month, year): """ Return (year, month, day) tuple that represents nth weekday of month in year. If n==0, returns last weekday of month. Weekdays: Monday=0 """ if not 0 <= n <= 5: raise IndexError("Nth day of month must be 0-5. Received: {}".format(n)) if not 0 <= weekday <= 6: raise IndexError("Weekday must be 0-6") firstday, daysinmonth = calendar.monthrange(year, month) # Get first WEEKDAY of month first_weekday_of_kind = 1 + (weekday - firstday) % 7 if n == 0: # find last weekday of kind, which is 5 if these conditions are met, else 4 if first_weekday_of_kind in [1, 2, 3] and first_weekday_of_kind + 28 <= daysinmonth: n = 5 else: n = 4 day = first_weekday_of_kind + ((n - 1) * 7) if day > daysinmonth: raise IndexError("No {}th day of month {}".format(n, month)) return (year, month, day)
Example #12
Source File: utils.py From convertdate with MIT License | 5 votes |
def n_weeks(weekday, jd, nthweek): j = 7 * nthweek if nthweek > 0: j += previous_weekday(weekday, jd) else: j += next_weekday(weekday, jd) return j
Example #13
Source File: utils.py From convertdate with MIT License | 5 votes |
def previous_or_current_weekday(weekday, jd): return search_weekday(weekday, jd, 1, 0)
Example #14
Source File: utils.py From convertdate with MIT License | 5 votes |
def previous_weekday(weekday, jd): return search_weekday(weekday, jd, -1, 1)
Example #15
Source File: utils.py From convertdate with MIT License | 5 votes |
def next_weekday(weekday, jd): return search_weekday(weekday, jd, 1, 7)
Example #16
Source File: utils.py From convertdate with MIT License | 5 votes |
def nearest_weekday(weekday, jd): return search_weekday(weekday, jd, 1, 3)
Example #17
Source File: utils.py From convertdate with MIT License | 5 votes |
def search_weekday(weekday, jd, direction, offset): '''Determine the Julian date for the next or previous weekday''' return weekday_before(weekday, jd + (direction * offset)) # Utility weekday functions, just wrappers for search_weekday
Example #18
Source File: utils.py From convertdate with MIT License | 5 votes |
def weekday_before(weekday, jd): return jd - jwday(jd - weekday) # @param weekday Day of week desired, 0 = Monday # @param jd Julian date to begin search # @param direction 1 = next weekday, -1 = last weekday # @param offset Offset from jd to begin search
Example #19
Source File: utils.py From convertdate with MIT License | 5 votes |
def amod(a, b): '''Modulus function which returns numerator if modulus is zero''' modded = int(a % b) return b if modded == 0 else modded # Sane people of the world, use calendar.weekday!
Example #20
Source File: parser.py From dateparser with BSD 3-Clause "New" or "Revised" License | 4 votes |
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: if self.now < dateobj: if 'past' in self.settings.PREFER_DATES_FROM: dateobj = dateobj.replace(year=dateobj.year - 1) else: if 'future' in self.settings.PREFER_DATES_FROM: dateobj = dateobj.replace(year=dateobj.year + 1) 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
Example #21
Source File: executor.py From CUP with Apache License 2.0 | 4 votes |
def __init__( self, name, pytz_timezone, timer_dict, md5uuid, function, *args, **kwargs ): """ :param pytz_timezone: which can be initialized like: tz = pytz.timezone('Asia/Beijing') :param timer_dict: { 'minute': minute_list, 'hour': hour_list, 'weekday': weekday_list, # [1~7] 'monthday': monday_list, # [1~31] 'month': month_list, # [1~12, 1~12] } # None stands for all valid, don't consider this field :param function: function that to be scheduled :param args: args of function :param kwargs: key args of function :raise: ValueError if function is not callable """ if not callable(function): raise ValueError('param function should be callable') if not isinstance(pytz_timezone, pytz.BaseTzInfo): raise ValueError('not a valid pytz timezone') self._name = name self._funcargs = (function, args, kwargs) self._pytz = pytz_timezone self._timer_dict = timer_dict if not all([ 'minute' in timer_dict, 'hour' in timer_dict, 'weekday' in timer_dict, 'monthday' in timer_dict, 'month' in timer_dict ]): raise ValueError('keys ' '(minute hour weekday monthday month should be in dict)' ) self._timer_params = self._generate_timer_params(self._timer_dict) self._check_param_valids(self._timer_params) self._lastsched_time = None if md5uuid is None: self._md5_id = self._GEN.get_uuid()[0] else: self._md5_id = md5uuid self._timer = None
Example #22
Source File: executor.py From CUP with Apache License 2.0 | 4 votes |
def next_schedtime(self, starting_fromdate=None): """ return next schedule time with timezone enabled. """ if starting_fromdate is None: tmp = datetime.datetime.now() datenow = self._pytz.localize(tmp) else: datenow = starting_fromdate tmp_dict = { 'year': datenow.year, 'month': datenow.month, 'monthday': datenow.day, 'weekday': datenow.isoweekday(), 'hour': datenow.hour, 'minute': datenow.minute + 1 } timer_params = copy.deepcopy(self._timer_params) maxtimes = 365 * 24 * 60 while True: if tmp_dict['month'] in timer_params['month']: if self.check_monthday_weekday( tmp_dict, timer_params ): if tmp_dict['hour'] in timer_params['hour']: if tmp_dict['minute'] in timer_params['minute']: break else: self.next_minute(tmp_dict, self._timer_params) maxtimes -= 1 if maxtimes < 0: log.warn( 'No valid datetime in a year' 'for crontask {0}'.format(self) ) return None else: self.next_hour(tmp_dict, self._timer_params) else: self.next_monthday_weekday(tmp_dict, self._timer_params) else: self.next_month(tmp_dict, timer_params) local_dt = self._pytz.localize(datetime.datetime( year=tmp_dict['year'], month=tmp_dict['month'], day=tmp_dict['monthday'], hour=tmp_dict['hour'], minute=tmp_dict['minute'] )) self.set_last_schedtime(local_dt) return local_dt