本文整理匯總了Python中dateutil.relativedelta方法的典型用法代碼示例。如果您正苦於以下問題:Python dateutil.relativedelta方法的具體用法?Python dateutil.relativedelta怎麽用?Python dateutil.relativedelta使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類dateutil
的用法示例。
在下文中一共展示了dateutil.relativedelta方法的11個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: testImportedModules
# 需要導入模塊: import dateutil [as 別名]
# 或者: from dateutil import relativedelta [as 別名]
def testImportedModules(self):
import dateutil.easter
import dateutil.parser
import dateutil.relativedelta
import dateutil.rrule
import dateutil.tz
import dateutil.utils
import dateutil.zoneinfo
self.assertEquals(dateutil.easter, new_locals.pop("easter"))
self.assertEquals(dateutil.parser, new_locals.pop("parser"))
self.assertEquals(dateutil.relativedelta, new_locals.pop("relativedelta"))
self.assertEquals(dateutil.rrule, new_locals.pop("rrule"))
self.assertEquals(dateutil.tz, new_locals.pop("tz"))
self.assertEquals(dateutil.utils, new_locals.pop("utils"))
self.assertEquals(dateutil.zoneinfo, new_locals.pop("zoneinfo"))
self.assertFalse(new_locals)
示例2: period
# 需要導入模塊: import dateutil [as 別名]
# 或者: from dateutil import relativedelta [as 別名]
def period(period_value, period_unit):
try:
from dateutil.relativedelta import relativedelta as period_impl
except Exception:
from datetime import timedelta as period_impl
if period_unit == 'nanoseconds':
period_unit = 'microseconds'
period_value = int(period_value / 1000)
arguments = dict(zip((period_unit,), (period_value,)))
if period_unit == 'milliseconds':
return timedelta(**arguments)
return period_impl(**arguments)
示例3: on_message_edit
# 需要導入模塊: import dateutil [as 別名]
# 或者: from dateutil import relativedelta [as 別名]
def on_message_edit(self, before: Message, after: Message) -> None:
"""
Invoke message filter for message edits.
If there have been multiple edits, calculate the time delta from the previous edit.
"""
if not before.edited_at:
delta = relativedelta(after.edited_at, before.created_at).microseconds
else:
delta = relativedelta(after.edited_at, before.edited_at).microseconds
await self._filter_message(after, delta)
示例4: testRelativeDeltaAll
# 需要導入模塊: import dateutil [as 別名]
# 或者: from dateutil import relativedelta [as 別名]
def testRelativeDeltaAll(self):
from dateutil.relativedelta import relativedelta
from dateutil.relativedelta import MO, TU, WE, TH, FR, SA, SU
for var in (relativedelta, MO, TU, WE, TH, FR, SA, SU):
self.assertIsNot(var, None)
# In the public interface but not in all
from dateutil.relativedelta import weekday
self.assertIsNot(weekday, None)
示例5: request_extension
# 需要導入模塊: import dateutil [as 別名]
# 或者: from dateutil import relativedelta [as 別名]
def request_extension(request):
student = Student.objects.get(user = request.user)
assignment_id = request.GET.get('aid')
selected_assignment = Assignment.objects.get(id=assignment_id)
logging.warn("Processing extension request for: " + str(student) + " on "
+ str(assignment_id) + " - " + str(selected_assignment))
now_time = timezone.now()
due_date = selected_assignment.corrected_due_date(student)
# late_delta = dateutil.relativedelta.relativedelta(now_time, due_date)
late_delta = now_time - due_date
late_days_needed = late_delta.days + 1 # a second above is a full day
late_days_left = student.get_late_days_left(selected_assignment.course)
if not due_date > now_time:
if late_days_needed <= late_days_left:
extension = AssignmentExtension(assignment=selected_assignment, student = student, days=late_days_needed)
extension.save()
status = 200
out = "Your extension request has been processed succesfully. "
else:
status = 500
out = "Insufficient number of late days remaining. Cannot process extension request. "
else:
status = 500
out = "There is still time left in assignment submission. Cannot process extension request. "
return HttpResponse(out, content_type="text/plain", status=status)
示例6: get_property
# 需要導入模塊: import dateutil [as 別名]
# 或者: from dateutil import relativedelta [as 別名]
def get_property(self, qtype, subject, prop):
"""Gets property of subject from Wikidata
Args:
qtype: Type of question (which, how many)
subject: Name of entity to get property of
prop: Property to get of subject
Returns:
WikiDataAnswer: Answer from result
"""
prop_id = None
if prop is None:
return self._get_desc(subject)
if prop == 'age':
bday_ans = self._get_property(subject, 'date of birth', 'P569')
if not bday_ans:
return None
import pdb;pdb.set_trace()
birthday = bday_ans.data[0]
years = relativedelta(datetime.now(), birthday).years
bday_ans.data = years
return bday_ans
if prop == 'born':
if qtype == 'where':
prop_id = 'P19'
elif qtype == 'when':
prop_id = 'P569'
if prop == 'height':
prop_id = 'P2044,P2048'
if prop in ['nickname', 'known as', 'alias', 'called']:
return self._get_aliases(subject)
return self._get_property(subject, prop, prop_id=prop_id)
示例7: get_supported_period_type_map
# 需要導入模塊: import dateutil [as 別名]
# 或者: from dateutil import relativedelta [as 別名]
def get_supported_period_type_map(cls):
if cls.supported_period_map is None:
cls.supported_period_map = {}
cls.supported_period_map.update(cls.period_type_map)
try:
from dateutil import relativedelta
if relativedelta is not None:
cls.supported_period_map.update(cls.optional_period_type_map)
except Exception:
pass
return cls.supported_period_map
示例8: cull_members_sheet
# 需要導入模塊: import dateutil [as 別名]
# 或者: from dateutil import relativedelta [as 別名]
def cull_members_sheet():
"""Deletes defunct members from the members sheet.
"""
# NOTE: The Google Spreadsheet API for deleting a row is stupid,
# inconsistent, and dangerous. It's incredibly easy to accidentally
# delete rows that you didn't intend to delete.
# For example, see the comment about `If-Match` in _delete_list_entry().
# So we're going to do this in the safest, dumbest way possible: We're
# going to retrieve the entire spreadsheet, find a single row to delete,
# delete it, and then re-fetch the entire spreadsheet again, etc.
# We're going to make this even dumber by sending a taskqueue request to
# ourself instead of actually looping. We're doing it that because I'm
# afraid that this approach is so slow and dumb that it will exceed the
# task time limit. (Although it probably won't.) And because maybe it's
# more robust that way.
#
# The fact that this task can be triggered by cron *and* by taskqueue
# probably means that there's a possibility of multiple threads of them
# running at the same time. Which would be bad. But improbable. Remember
# that in a normal run there will be at most one member to delete.
older_than = datetime.datetime.now() - relativedelta(years=2, months=1)
cull_entries = _get_members_renewed_ago(None, older_than)
if not cull_entries:
return
for entry in cull_entries:
logging.info('cull_members_sheet: deleting: %s' % entry.to_dict())
_delete_list_entry(entry)
# Queue up another call
taskqueue.add(url='/tasks/member-sheet-cull')
# We've done one and queued up another -- stop
return
示例9: get_members_expiring_soon
# 需要導入模塊: import dateutil [as 別名]
# 或者: from dateutil import relativedelta [as 別名]
def get_members_expiring_soon():
"""Returns a list of list-entries of members expiring soon.
"""
# We want members whose membership will be expiring in a week. This means
# getting members who were last renewed one year less a week ago. We
# check daily, so we'll get members in a day-long window.
after_datetime = datetime.datetime.now() + relativedelta(years=-1, days=6)
before_datetime = datetime.datetime.now() + relativedelta(years=-1, days=7)
expiring_entries = _get_members_renewed_ago(after_datetime, before_datetime)
return expiring_entries or []
示例10: get_fuzzy_padding
# 需要導入模塊: import dateutil [as 別名]
# 或者: from dateutil import relativedelta [as 別名]
def get_fuzzy_padding(self, object):
padding_day_precision = relativedelta(days=self.fuzzy_day_padding).normalized()
padding_month_precision = relativedelta(months=self.fuzzy_month_padding).normalized()
padding_year_precision = relativedelta(years=self.fuzzy_year_padding).normalized()
padding_season_precision = relativedelta(weeks=self.fuzzy_season_padding).normalized()
if isinstance(object, UncertainOrApproximate):
# from https://github.com/ixc/python-edtf/blob/master/edtf/parser/parser_classes.py#L366
if not object.ua:
return relativedelta(0)
multiplier = object.ua._get_multiplier()
if object.date.precision == PRECISION_DAY:
result = multiplier * padding_day_precision
elif object.date.precision == PRECISION_MONTH:
result = multiplier * padding_month_precision
elif object.date.precision == PRECISION_YEAR:
result = multiplier * padding_year_precision
return result
elif isinstance(object, PartialUncertainOrApproximate):
# from https://github.com/ixc/python-edtf/blob/master/edtf/parser/parser_classes.py#L528
result = relativedelta(0)
if object.year_ua:
result += padding_year_precision * object.year_ua._get_multiplier()
if object.month_ua:
result += padding_month_precision * object.month_ua._get_multiplier()
if object.day_ua:
result += padding_day_precision * object.day_ua._get_multiplier()
if object.year_month_ua:
result += padding_year_precision * object.year_month_ua._get_multiplier()
result += padding_month_precision * object.year_month_ua._get_multiplier()
if object.month_day_ua:
result += padding_day_precision * object.month_day_ua._get_multiplier()
result += padding_month_precision * object.month_day_ua._get_multiplier()
if object.season_ua:
result += padding_season_precision * object.season_ua._get_multiplier()
if object.all_ua:
multiplier = object.all_ua._get_multiplier()
if object.precision == PRECISION_DAY:
result += multiplier * padding_day_precision
result += multiplier * padding_month_precision
result += multiplier * padding_year_precision
elif object.precision == PRECISION_MONTH:
result += multiplier * padding_month_precision
result += multiplier * padding_year_precision
elif object.precision == PRECISION_YEAR:
result += multiplier * padding_year_precision
return result
return None
示例11: dateutil_parse
# 需要導入模塊: import dateutil [as 別名]
# 或者: from dateutil import relativedelta [as 別名]
def dateutil_parse(timestr, default,
ignoretz=False, tzinfos=None,
**kwargs):
""" lifted from dateutil to get resolution"""
from dateutil import tz
import time
fobj = StringIO(str(timestr))
res = DEFAULTPARSER._parse(fobj, **kwargs)
# dateutil 2.2 compat
if isinstance(res, tuple):
res, _ = res
if res is None:
raise ValueError("unknown string format")
repl = {}
reso = None
for attr in ["year", "month", "day", "hour",
"minute", "second", "microsecond"]:
value = getattr(res, attr)
if value is not None:
repl[attr] = value
reso = attr
if reso is None:
raise ValueError("Cannot parse date.")
if reso == 'microsecond' and repl['microsecond'] == 0:
reso = 'second'
ret = default.replace(**repl)
if res.weekday is not None and not res.day:
ret = ret + relativedelta.relativedelta(weekday=res.weekday)
if not ignoretz:
if callable(tzinfos) or tzinfos and res.tzname in tzinfos:
if callable(tzinfos):
tzdata = tzinfos(res.tzname, res.tzoffset)
else:
tzdata = tzinfos.get(res.tzname)
if isinstance(tzdata, datetime.tzinfo):
tzinfo = tzdata
elif isinstance(tzdata, compat.string_types):
tzinfo = tz.tzstr(tzdata)
elif isinstance(tzdata, int):
tzinfo = tz.tzoffset(res.tzname, tzdata)
else:
raise ValueError("offset must be tzinfo subclass, "
"tz string, or int offset")
ret = ret.replace(tzinfo=tzinfo)
elif res.tzname and res.tzname in time.tzname:
ret = ret.replace(tzinfo=tz.tzlocal())
elif res.tzoffset == 0:
ret = ret.replace(tzinfo=tz.tzutc())
elif res.tzoffset:
ret = ret.replace(tzinfo=tz.tzoffset(res.tzname, res.tzoffset))
return ret, reso