def _testWeekday(self, loc, interval): if self._starts_on_sunday(loc): self.assertEqual(relativedelta.weekday(interval[0].weekday()), SU) self.assertEqual(relativedelta.weekday(interval[1].weekday()), SA) else: self.assertEqual(relativedelta.weekday(interval[0].weekday()), MO) self.assertEqual(relativedelta.weekday(interval[1].weekday()), SU)
def get_datetime_ranges(base_datetime, granularity): """ Returns a datetime ranges for the given granularity based on the given datetime. :param base_datetime: a datetime to deduce range :param granularity: the type of range to deduce :return: tuple, a datetime ranges """ start = end = None if granularity == GRANULARITY_WEEK: week_day = get_weekday() start = base_datetime + relativedelta( weekday=weekday(week_day, n=-1), hour=0, minute=0, second=0, microsecond=0, ) end = base_datetime + relativedelta( weekday=weekday(week_day, n=-1), weeks=1, hour=0, minute=0, second=0, microsecond=0, ) # Cannot use it above because day is not changed. Another way? end += relativedelta(seconds=-1) elif granularity == GRANULARITY_MONTH: # pragma: no branch start = base_datetime + relativedelta( day=1, hour=0, minute=0, second=0, microsecond=0, ) end = base_datetime + relativedelta( months=1, seconds=-1, day=1, hour=0, minute=0, second=0, microsecond=0, ) return start, end
def test_first_last_day_semester_summer(): """This test is static""" from dateutil import relativedelta as rdelta first_day, last_day = course.first_last_day_semester( 'summer_4A', rdelta.weekday(3)) from datetime import date assert first_day == date(2014, 5, 8) assert last_day == '20140624'
def test_first_last_day_semester_fall(): """This test is static""" from dateutil import relativedelta as rdelta first_day, last_day = course.first_last_day_semester( 'fall', rdelta.weekday(0)) from datetime import date assert first_day == date(2014, 9, 8) assert last_day == '20141202'
def _auto_gen_weekly(): filename = (date.today() + relativedelta( weekday=weekday(0, -1))).strftime('%Y%m%d Week.md') filename = os.path.join( os.path.dirname(os.path.dirname(MarkdownPreview.__file__)), 'posts', filename) if not os.path.exists(filename): open(filename, 'w').write(open('posts/default.md').read())
def get(self): filename = (date.today() + relativedelta( weekday=weekday(0, -1))).strftime('%Y%m%d Week.md') filename = os.path.join( os.path.dirname(os.path.dirname(MarkdownPreview.__file__)), 'posts', filename) _auto_gen_weekly() html = MarkdownPreview.MarkdownPreviewCommand( filename ).run().encode('utf-8') self.write(html)
def next_lunch_date(): next_thursday = rrule.rrule(rrule.MONTHLY, byweekday=relativedelta.weekday(LUNCH_WEEKDAY), byhour=LUNCH_HOUR, dtstart=date.today(), count=2) next_date = next_thursday[0] # doing this check manually is an artifact of not (yet) correctly # handling the timezone if next_date < datetime.now(): next_date = next_thursday[1] return next_date.ctime()
def get(self, week): if week == 'favicon.ico': return week = '%d%s' % (date.today().year, week) if len(week) <= 4 else week filename = (parse(week) + relativedelta( weekday=weekday(0, -1))).strftime('%Y%m%d Week.md') filename = os.path.join( os.path.dirname(os.path.dirname(MarkdownPreview.__file__)), 'posts', filename) _auto_gen_weekly() html = MarkdownPreview.MarkdownPreviewCommand( filename ).run().encode('utf-8') self.write(html)
def _delta(self, x, isend=0): from dateutil import relativedelta kwargs = {} if x.month is not None: kwargs["month"] = x.month if x.weekday is not None: kwargs["weekday"] = relativedelta.weekday(x.weekday, x.week) if x.week > 0: kwargs["day"] = 1 else: kwargs["day"] = 31 elif x.day: kwargs["day"] = x.day elif x.yday is not None: kwargs["yearday"] = x.yday elif x.jyday is not None: kwargs["nlyearday"] = x.jyday if not kwargs: # Default is to start on first sunday of april, and end # on last sunday of october. if not isend: kwargs["month"] = 4 kwargs["day"] = 1 kwargs["weekday"] = relativedelta.SU(+1) else: kwargs["month"] = 10 kwargs["day"] = 31 kwargs["weekday"] = relativedelta.SU(-1) if x.time is not None: kwargs["seconds"] = x.time else: # Default is 2AM. kwargs["seconds"] = 7200 if isend: # Convert to standard time, to follow the documented way # of working with the extra hour. See the documentation # of the tzinfo class. delta = self._dst_offset - self._std_offset kwargs["seconds"] -= delta.seconds + delta.days * 86400 return relativedelta.relativedelta(**kwargs)
def _deserialize(cls, encoded_var): # pylint: disable=too-many-return-statements """Helper function of depth first search for deserialization.""" from airflow.serialization.serialized_dag import SerializedDAG from airflow.serialization.serialized_baseoperator import SerializedBaseOperator # JSON primitives (except for dict) are not encoded. if cls._is_primitive(encoded_var): return encoded_var elif isinstance(encoded_var, list): return [cls._deserialize(v) for v in encoded_var] assert isinstance(encoded_var, dict) var = encoded_var[Encoding.VAR] type_ = encoded_var[Encoding.TYPE] if type_ == DAT.DICT: return {k: cls._deserialize(v) for k, v in var.items()} elif type_ == DAT.DAG: return SerializedDAG.deserialize_dag(var) elif type_ == DAT.OP: return SerializedBaseOperator.deserialize_operator(var) elif type_ == DAT.DATETIME: return pendulum.from_timestamp(var) elif type_ == DAT.TIMEDELTA: return datetime.timedelta(seconds=var) elif type_ == DAT.TIMEZONE: return pendulum.timezone(var) elif type_ == DAT.RELATIVEDELTA: if 'weekday' in var: var['weekday'] = relativedelta.weekday(*var['weekday']) return relativedelta.relativedelta(**var) elif type_ == DAT.SET: return {cls._deserialize(v) for v in var} elif type_ == DAT.TUPLE: return tuple([cls._deserialize(v) for v in var]) else: raise TypeError( 'Invalid type {!s} in deserialization.'.format(type_))
def get_weekday_start(): """Returns the dateutil.relativedelta.weekday based on the current locale. :returns: a dateutil.realtivedelta.weekday instance """ _system = platform.system() week_start = 0 if _system == 'Darwin': # FIXME: Port this to use py objc # http://stackoverflow.com/questions/3519207/how-to-calculate-first-nsdate-of-current-week pass elif _system == 'Windows': # FIXME: GetLocaleInfo(LOCALE_IFIRSTDAYOFWEEK) pass elif _system == 'Linux': # Libc + ctypes is not working on natty and previous # libc = get_libc() # week_origin = libc.nl_langinfo(NL_TIME_WEEK_1STDAY) # v = libc.nl_langinfo(NL_TIME_FIRST_WEEKDAY) # first_weekday = ord(ctypes.cast(v, ctypes.c_char_p).value[0]) process = os.popen("locale first_weekday week-1stday") first_weekday, week_origin = process.read().split('\n')[:2] process.close() # we will set week_1sday based on the dateutil.relativedelta.weekday mapping if week_origin == '19971130': # Sunday week_1stday = 6 elif week_origin == '19971201': # Monday week_1stday = 0 else: raise TypeError('Unknown NL_TIME_WEEK_1STDAY constant') week_start = (week_1stday + int(first_weekday) - 1) % 7 return relativedelta.weekday(week_start)
def test_appointments_creation_dates2(self): """Assert skips SA, SU. """ self.register_visit_schedule(facility_name='5-day-clinic') base_appt_datetime = datetime(2017, 1, 7) self.assertTrue(weekday(base_appt_datetime.weekday()), SA) appt_datetimes = self.get_appt_datetimes( base_appt_datetime=base_appt_datetime, subject_identifier=f'123456') self.assertTrue(weekday(appt_datetimes[0].weekday()), MO) self.assertTrue(weekday(appt_datetimes[1].weekday()), TU) self.assertTrue(weekday(appt_datetimes[2].weekday()), WE) self.assertTrue(weekday(appt_datetimes[3].weekday()), TH) base_appt_datetime = datetime(2017, 1, 8) self.assertTrue(weekday(base_appt_datetime.weekday()), SU) appt_datetimes = self.get_appt_datetimes( base_appt_datetime=base_appt_datetime, subject_identifier=f'1234567') self.assertTrue(weekday(appt_datetimes[0].weekday()), MO) self.assertTrue(weekday(appt_datetimes[1].weekday()), TU) self.assertTrue(weekday(appt_datetimes[2].weekday()), WE) self.assertTrue(weekday(appt_datetimes[3].weekday()), TH) base_appt_datetime = datetime(2017, 1, 9) self.assertTrue(weekday(base_appt_datetime.weekday()), MO) appt_datetimes = self.get_appt_datetimes( base_appt_datetime=base_appt_datetime, subject_identifier=f'12345678') self.assertTrue(weekday(appt_datetimes[0].weekday()), MO) self.assertTrue(weekday(appt_datetimes[1].weekday()), TU) self.assertTrue(weekday(appt_datetimes[2].weekday()), WE) self.assertTrue(weekday(appt_datetimes[3].weekday()), TH) base_appt_datetime = datetime(2017, 1, 10) self.assertTrue(weekday(base_appt_datetime.weekday()), TU) appt_datetimes = self.get_appt_datetimes( base_appt_datetime=base_appt_datetime, subject_identifier=f'123456789') self.assertTrue(weekday(appt_datetimes[0].weekday()), TU) self.assertTrue(weekday(appt_datetimes[1].weekday()), WE) self.assertTrue(weekday(appt_datetimes[2].weekday()), TH) self.assertTrue(weekday(appt_datetimes[3].weekday()), FR) base_appt_datetime = datetime(2017, 1, 11) self.assertTrue(weekday(base_appt_datetime.weekday()), WE) appt_datetimes = self.get_appt_datetimes( base_appt_datetime=base_appt_datetime, subject_identifier=f'1234567890') self.assertTrue(weekday(appt_datetimes[0].weekday()), WE) self.assertTrue(weekday(appt_datetimes[1].weekday()), TH) self.assertTrue(weekday(appt_datetimes[2].weekday()), FR) self.assertTrue(weekday(appt_datetimes[3].weekday()), MO)
def decode_relativedelta(var: Dict[str, Any]) -> relativedelta.relativedelta: if 'weekday' in var: var['weekday'] = relativedelta.weekday(*var['weekday']) # type: ignore return relativedelta.relativedelta(**var)
def previous_date(self): return self.date + relativedelta( weekday=weekday(self.week_day, n=-1), weeks=-1, )
def next_date(self): return self.date + relativedelta( weekday=weekday(self.week_day, n=-1), weeks=1, )