本文整理汇总了Python中dateutil.relativedelta.relativedelta方法的典型用法代码示例。如果您正苦于以下问题:Python relativedelta.relativedelta方法的具体用法?Python relativedelta.relativedelta怎么用?Python relativedelta.relativedelta使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类dateutil.relativedelta
的用法示例。
在下文中一共展示了relativedelta.relativedelta方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __new__
# 需要导入模块: from dateutil import relativedelta [as 别名]
# 或者: from dateutil.relativedelta import relativedelta [as 别名]
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))
示例2: _get_index_weight_range
# 需要导入模块: from dateutil import relativedelta [as 别名]
# 或者: from dateutil.relativedelta import relativedelta [as 别名]
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)
示例3: setup
# 需要导入模块: from dateutil import relativedelta [as 别名]
# 或者: from dateutil.relativedelta import relativedelta [as 别名]
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)
示例4: smm_test_data
# 需要导入模块: from dateutil import relativedelta [as 别名]
# 或者: from dateutil.relativedelta import relativedelta [as 别名]
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)
示例5: previous_months_iterator
# 需要导入模块: from dateutil import relativedelta [as 别名]
# 或者: from dateutil.relativedelta import relativedelta [as 别名]
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)
示例6: backfill_monthly_metrics_for_site
# 需要导入模块: from dateutil import relativedelta [as 别名]
# 或者: from dateutil.relativedelta import relativedelta [as 别名]
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
示例7: __init__
# 需要导入模块: from dateutil import relativedelta [as 别名]
# 或者: from dateutil.relativedelta import relativedelta [as 别名]
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()
示例8: get_initial
# 需要导入模块: from dateutil import relativedelta [as 别名]
# 或者: from dateutil.relativedelta import relativedelta [as 别名]
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
示例9: get_context_data
# 需要导入模块: from dateutil import relativedelta [as 别名]
# 或者: from dateutil.relativedelta import relativedelta [as 别名]
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
示例10: on_member_join
# 需要导入模块: from dateutil import relativedelta [as 别名]
# 或者: from dateutil.relativedelta import relativedelta [as 别名]
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
)
示例11: until_expiration
# 需要导入模块: from dateutil import relativedelta [as 别名]
# 或者: from dateutil.relativedelta import relativedelta [as 别名]
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)
示例12: test_all_single_orbit_calls_in_day
# 需要导入模块: from dateutil import relativedelta [as 别名]
# 或者: from dateutil.relativedelta import relativedelta [as 别名]
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)
示例13: _build_naive
# 需要导入模块: from dateutil import relativedelta [as 别名]
# 或者: from dateutil.relativedelta import relativedelta [as 别名]
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
示例14: testInheritance
# 需要导入模块: from dateutil import relativedelta [as 别名]
# 或者: from dateutil.relativedelta import relativedelta [as 别名]
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.')
示例15: testMonthsOfDiffNumOfDaysWithYears
# 需要导入模块: from dateutil import relativedelta [as 别名]
# 或者: from dateutil.relativedelta import relativedelta [as 别名]
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))