Python dateutil.relativedelta.relativedelta() Examples
The following are 30
code examples of dateutil.relativedelta.relativedelta().
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
dateutil.relativedelta
, or try the search function
.
Example #1
Source File: __init__.py From aegea with Apache License 2.0 | 9 votes |
def __new__(cls, t, snap=0): if isinstance(t, (str, bytes)) and t.isdigit(): t = int(t) if not isinstance(t, (str, bytes)): from dateutil.tz import tzutc return datetime.fromtimestamp(t // 1000, tz=tzutc()) try: units = ["weeks", "days", "hours", "minutes", "seconds"] diffs = {u: float(t[:-1]) for u in units if u.startswith(t[-1])} if len(diffs) == 1: # Snap > 0 governs the rounding of units (hours, minutes and seconds) to 0 to improve cache performance snap_units = {u.rstrip("s"): 0 for u in units[units.index(list(diffs)[0]) + snap:]} if snap else {} snap_units.pop("day", None) snap_units.update(microsecond=0) ts = datetime.now().replace(**snap_units) + relativedelta(**diffs) cls._precision[ts] = snap_units return ts return dateutil_parse(t) except (ValueError, OverflowError, AssertionError): raise ValueError('Could not parse "{}" as a timestamp or time delta'.format(t))
Example #2
Source File: helpers.py From figures with MIT License | 7 votes |
def previous_months_iterator(month_for, months_back): '''Iterator returns a year,month tuple for n months including the month_for month_for is either a date, datetime, or tuple with year and month months back is the number of months to iterate includes the month_for ''' if isinstance(month_for, tuple): # TODO make sure we've got just two values in the tuple month_for = datetime.date(year=month_for[0], month=month_for[1], day=1) if isinstance(month_for, (datetime.datetime, datetime.date)): start_month = month_for - relativedelta(months=months_back) for dt in rrule(freq=MONTHLY, dtstart=start_month, until=month_for): last_day_of_month = days_in_month(month_for=dt) yield (dt.year, dt.month, last_day_of_month)
Example #3
Source File: test_site_monthly_metrics.py From figures with MIT License | 6 votes |
def smm_test_data(db): """ Minimal test data for very simple test case """ site = SiteFactory() mock_today = datetime(year=2020, month=2, day=1, tzinfo=utc) last_month = mock_today - relativedelta(months=1) month_before = last_month - relativedelta(months=1) month_before_sm = [StudentModuleFactory(created=month_before, modified=month_before)] last_month_sm = [StudentModuleFactory(created=last_month, modified=last_month) for i in range(2)] return dict(site=site, mock_today=mock_today, last_month=last_month, month_before=month_before, last_month_sm=last_month_sm, month_before_sm=month_before_sm)
Example #4
Source File: test_enrollment_metrics.py From figures with MIT License | 6 votes |
def setup(self, db): self.site = SiteFactory() self.date_1 = datetime(2020, 2, 2, tzinfo=utc) self.date_2 = self.date_1 + relativedelta(months=1) # future of date_1 self.course_enrollment = CourseEnrollmentFactory() self.student_modules = [ StudentModuleFactory(student=self.course_enrollment.user, course_id=self.course_enrollment.course_id, modified=self.date_1), StudentModuleFactory(student=self.course_enrollment.user, course_id=self.course_enrollment.course_id, modified=self.date_2)] self.progress_data = dict(points_possible=100, points_earned=25, sections_worked=4, count=5)
Example #5
Source File: test_relativedelta.py From plugin.video.emby with GNU General Public License v3.0 | 6 votes |
def testInheritance(self): # Ensure that relativedelta is inheritance-friendly. class rdChildClass(relativedelta): pass ccRD = rdChildClass(years=1, months=1, days=1, leapdays=1, weeks=1, hours=1, minutes=1, seconds=1, microseconds=1) rd = relativedelta(years=1, months=1, days=1, leapdays=1, weeks=1, hours=1, minutes=1, seconds=1, microseconds=1) self.assertEqual(type(ccRD + rd), type(ccRD), msg='Addition does not inherit type.') self.assertEqual(type(ccRD - rd), type(ccRD), msg='Subtraction does not inherit type.') self.assertEqual(type(-ccRD), type(ccRD), msg='Negation does not inherit type.') self.assertEqual(type(ccRD * 5.0), type(ccRD), msg='Multiplication does not inherit type.') self.assertEqual(type(ccRD / 5.0), type(ccRD), msg='Division does not inherit type.')
Example #6
Source File: universal.py From xalpha with MIT License | 6 votes |
def _get_index_weight_range(code, start, end): if len(code.split(".")) != 2: code = _inverse_convert_code(code) start_obj = dt.datetime.strptime(start.replace("-", "").replace("/", ""), "%Y%m%d") end_obj = dt.datetime.strptime(end.replace("-", "").replace("/", ""), "%Y%m%d") start_m = start_obj.replace(day=1) if start_m < start_obj: start_m = start_m + relativedelta(months=1) end_m = end_obj.replace(day=1) if end_obj < end_m: end_m = end_m - relativedelta(months=1) d = start_m df = pd.DataFrame({"code": [], "weight": [], "display_name": [], "date": []}) while True: if d > end_m: df["date"] = pd.to_datetime(df["date"]) return df logger.debug("fetch index weight on %s for %s" % (d, code)) df0 = get_index_weights(index_id=code, date=d.strftime("%Y-%m-%d")) df0["code"] = df0.index df = df.append(df0, ignore_index=True, sort=False) d = d + relativedelta(months=1)
Example #7
Source File: backfill.py From figures with MIT License | 6 votes |
def backfill_monthly_metrics_for_site(site, overwrite=False): """Backfill all historical site metrics for the specified site """ site_sm = get_student_modules_for_site(site) if not site_sm: return None first_created = site_sm.order_by('created').first().created start_month = datetime(year=first_created.year, month=first_created.month, day=1, tzinfo=utc) last_month = datetime.utcnow().replace(tzinfo=utc) - relativedelta(months=1) backfilled = [] for dt in rrule(freq=MONTHLY, dtstart=start_month, until=last_month): obj, created = fill_month(site=site, month_for=dt, student_modules=site_sm, overwrite=overwrite) backfilled.append(dict(obj=obj, created=created, dt=dt)) return backfilled
Example #8
Source File: wrappers.py From django-accounting with MIT License | 6 votes |
def __init__(self, organization, start, end): super().__init__("Profit and Loss", start, end) self.organization = organization self.summaries = {} steps_interval = relativedelta(end, start) assert self.group_by_resolution in self.RESOLUTION_CHOICES, \ "No a resolution choice" if self.group_by_resolution == self.RESOLUTION_MONTHLY: for step in range(0, steps_interval.months): key_date = start + relativedelta(months=step) self.summaries[key_date] = ProfitAndLossSummary() else: raise ValueError("Unsupported resolution {}" .format(self.group_by_resolution)) self.total_summary = ProfitAndLossSummary()
Example #9
Source File: views.py From django-accounting with MIT License | 6 votes |
def get_initial(self): initial = super().get_initial() # currrent quarter now = timezone.now() start = date( year=now.year, month=(now.month - ((now.month - 1) % 3)), day=1 ) end = start + relativedelta(months=3) initial['date_from'] = start initial['date_to'] = end return initial
Example #10
Source File: modlog.py From bot with MIT License | 6 votes |
def on_member_join(self, member: discord.Member) -> None: """Log member join event to user log.""" if member.guild.id != GuildConstant.id: return member_str = escape_markdown(str(member)) message = f"{member_str} (`{member.id}`)" now = datetime.utcnow() difference = abs(relativedelta(now, member.created_at)) message += "\n\n**Account age:** " + humanize_delta(difference) if difference.days < 1 and difference.months < 1 and difference.years < 1: # New user account! message = f"{Emojis.new} {message}" await self.send_log_message( Icons.sign_in, Colours.soft_green, "User joined", message, thumbnail=member.avatar_url_as(static_format="png"), channel_id=Channels.user_log )
Example #11
Source File: time.py From bot with MIT License | 6 votes |
def until_expiration( expiry: Optional[str], now: Optional[datetime.datetime] = None, max_units: int = 2 ) -> Optional[str]: """ Get the remaining time until infraction's expiration, in a human-readable version of the relativedelta. Returns a human-readable version of the remaining duration between datetime.utcnow() and an expiry. Unlike `humanize_delta`, this function will force the `precision` to be `seconds` by not passing it. `max_units` specifies the maximum number of units of time to include (e.g. 1 may include days but not hours). By default, max_units is 2. """ if not expiry: return None now = now or datetime.datetime.utcnow() since = dateutil.parser.isoparse(expiry).replace(tzinfo=None, microsecond=0) if since < now: return None return humanize_delta(relativedelta(since, now), max_units=max_units)
Example #12
Source File: views.py From django-accounting with MIT License | 6 votes |
def get_context_data(self, **kwargs): ctx = super().get_context_data(**kwargs) orga = organization_manager.get_selected_organization(self.request) # currrent quarter now = timezone.now() start = date( year=now.year, month=(now.month - ((now.month - 1) % 3)), day=1 ) end = start + relativedelta(months=3) report = ProfitAndLossReport(orga, start=start, end=end) report.generate() ctx['summaries'] = report.summaries ctx['total_summary'] = report.total_summary return ctx
Example #13
Source File: test_orbits.py From pysat with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_all_single_orbit_calls_in_day(self): self.testInst.load(2009, 1) ans = [] ans2 = [] self.testInst.bounds = (pysat.datetime(2009, 1, 1), None) for i, inst in enumerate(self.testInst.orbits): if i > 14: break print('Loaded orbit ', self.testInst.orbits.current) ans.append(self.testInst.index[0] == (pds.datetime(2009, 1, 1) + i*relativedelta(hours=1, minutes=37))) ans2.append(self.testInst.index[-1] == (pds.datetime(2009, 1, 1) + (i + 1) * relativedelta(hours=1, minutes=37) - relativedelta(seconds=1))) assert np.all(ans) & np.all(ans2)
Example #14
Source File: _parser.py From plugin.video.emby with GNU General Public License v3.0 | 6 votes |
def _build_naive(self, res, default): repl = {} for attr in ("year", "month", "day", "hour", "minute", "second", "microsecond"): value = getattr(res, attr) if value is not None: repl[attr] = value if 'day' not in repl: # If the default day exceeds the last day of the month, fall back # to the end of the month. cyear = default.year if res.year is None else res.year cmonth = default.month if res.month is None else res.month cday = default.day if res.day is None else res.day if cday > monthrange(cyear, cmonth)[1]: repl['day'] = monthrange(cyear, cmonth)[1] naive = default.replace(**repl) if res.weekday is not None and not res.day: naive = naive + relativedelta.relativedelta(weekday=res.weekday) return naive
Example #15
Source File: test_relativedelta.py From plugin.video.emby with GNU General Public License v3.0 | 6 votes |
def testMonthsOfDiffNumOfDaysWithYears(self): self.assertEqual(date(2000, 2, 28)+relativedelta(years=+1), date(2001, 2, 28)) self.assertEqual(date(2000, 2, 29)+relativedelta(years=+1), date(2001, 2, 28)) self.assertEqual(date(1999, 2, 28)+relativedelta(years=+1), date(2000, 2, 28)) self.assertEqual(date(1999, 3, 1)+relativedelta(years=+1), date(2000, 3, 1)) self.assertEqual(date(1999, 3, 1)+relativedelta(years=+1), date(2000, 3, 1)) self.assertEqual(date(2001, 2, 28)+relativedelta(years=-1), date(2000, 2, 28)) self.assertEqual(date(2001, 3, 1)+relativedelta(years=-1), date(2000, 3, 1))
Example #16
Source File: test_relativedelta.py From plugin.video.emby with GNU General Public License v3.0 | 6 votes |
def testInequalityWeekdays(self): # Different weekdays no_wday = relativedelta(year=1997, month=4) wday_mo_1 = relativedelta(year=1997, month=4, weekday=MO(+1)) wday_mo_2 = relativedelta(year=1997, month=4, weekday=MO(+2)) wday_tu = relativedelta(year=1997, month=4, weekday=TU) self.assertTrue(wday_mo_1 == wday_mo_1) self.assertFalse(no_wday == wday_mo_1) self.assertFalse(wday_mo_1 == no_wday) self.assertFalse(wday_mo_1 == wday_mo_2) self.assertFalse(wday_mo_2 == wday_mo_1) self.assertFalse(wday_mo_1 == wday_tu) self.assertFalse(wday_tu == wday_mo_1)
Example #17
Source File: test_relativedelta.py From plugin.video.emby with GNU General Public License v3.0 | 5 votes |
def testMillenniumAge(self): self.assertEqual(relativedelta(self.now, date(2001, 1, 1)), relativedelta(years=+2, months=+8, days=+16, hours=+20, minutes=+54, seconds=+47, microseconds=+282310))
Example #18
Source File: test_relativedelta.py From plugin.video.emby with GNU General Public License v3.0 | 5 votes |
def test15thISOYearWeek(self): self.assertEqual(date(2003, 1, 1) + relativedelta(day=4, weeks=+14, weekday=MO(-1)), date(2003, 4, 7))
Example #19
Source File: test_relativedelta.py From plugin.video.emby with GNU General Public License v3.0 | 5 votes |
def testJohnAgeWithDate(self): self.assertEqual(relativedelta(self.today, datetime(1978, 4, 5, 12, 0)), relativedelta(years=+25, months=+5, days=+11, hours=+12))
Example #20
Source File: test_relativedelta.py From plugin.video.emby with GNU General Public License v3.0 | 5 votes |
def testNextWednesdayIsToday(self): self.assertEqual(self.today+relativedelta(weekday=WE), date(2003, 9, 17))
Example #21
Source File: test_relativedelta.py From plugin.video.emby with GNU General Public License v3.0 | 5 votes |
def testLastFridayInThisMonth(self): self.assertEqual(self.today+relativedelta(day=31, weekday=FR(-1)), date(2003, 9, 26))
Example #22
Source File: test_relativedelta.py From plugin.video.emby with GNU General Public License v3.0 | 5 votes |
def testNextFriday(self): self.assertEqual(self.today+relativedelta(weekday=FR), date(2003, 9, 19))
Example #23
Source File: test_relativedelta.py From plugin.video.emby with GNU General Public License v3.0 | 5 votes |
def testNextWenesdayNotToday(self): self.assertEqual(self.today+relativedelta(days=+1, weekday=WE), date(2003, 9, 24))
Example #24
Source File: test_relativedelta.py From plugin.video.emby with GNU General Public License v3.0 | 5 votes |
def testYearDay(self): self.assertEqual(date(2003, 1, 1)+relativedelta(yearday=260), date(2003, 9, 17)) self.assertEqual(date(2002, 1, 1)+relativedelta(yearday=260), date(2002, 9, 17)) self.assertEqual(date(2000, 1, 1)+relativedelta(yearday=260), date(2000, 9, 16)) self.assertEqual(self.today+relativedelta(yearday=261), date(2003, 9, 18))
Example #25
Source File: test_relativedelta.py From plugin.video.emby with GNU General Public License v3.0 | 5 votes |
def testYearDayBug(self): # Tests a problem reported by Adam Ryan. self.assertEqual(date(2010, 1, 1)+relativedelta(yearday=15), date(2010, 1, 15))
Example #26
Source File: test_relativedelta.py From plugin.video.emby with GNU General Public License v3.0 | 5 votes |
def testNonLeapYearDay(self): self.assertEqual(date(2003, 1, 1)+relativedelta(nlyearday=260), date(2003, 9, 17)) self.assertEqual(date(2002, 1, 1)+relativedelta(nlyearday=260), date(2002, 9, 17)) self.assertEqual(date(2000, 1, 1)+relativedelta(nlyearday=260), date(2000, 9, 17)) self.assertEqual(self.today+relativedelta(yearday=261), date(2003, 9, 18))
Example #27
Source File: test_relativedelta.py From plugin.video.emby with GNU General Public License v3.0 | 5 votes |
def testAddition(self): self.assertEqual(relativedelta(days=10) + relativedelta(years=1, months=2, days=3, hours=4, minutes=5, microseconds=6), relativedelta(years=1, months=2, days=13, hours=4, minutes=5, microseconds=6))
Example #28
Source File: test_relativedelta.py From plugin.video.emby with GNU General Public License v3.0 | 5 votes |
def testAdditionToDatetime(self): self.assertEqual(datetime(2000, 1, 1) + relativedelta(days=1), datetime(2000, 1, 2))
Example #29
Source File: test_relativedelta.py From plugin.video.emby with GNU General Public License v3.0 | 5 votes |
def testAdditionUnsupportedType(self): # For unsupported types that define their own comparators, etc. self.assertIs(relativedelta(days=1) + NotAValue, NotAValue)
Example #30
Source File: test_relativedelta.py From plugin.video.emby with GNU General Public License v3.0 | 5 votes |
def testRightAdditionToDatetime(self): self.assertEqual(relativedelta(days=1) + datetime(2000, 1, 1), datetime(2000, 1, 2))