Python dateutil.relativedelta() Examples

The following are 14 code examples of dateutil.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 , or try the search function .
Example #1
Source File: test_import_star.py    From plugin.video.emby with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #2
Source File: config_parser.py    From pyhocon with Apache License 2.0 6 votes vote down vote up
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) 
Example #3
Source File: config_parser.py    From trains with Apache License 2.0 6 votes vote down vote up
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) 
Example #4
Source File: filtering.py    From bot with MIT License 5 votes vote down vote up
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) 
Example #5
Source File: test_imports.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
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) 
Example #6
Source File: views.py    From AutoGrader with MIT License 5 votes vote down vote up
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) 
Example #7
Source File: wikidata.py    From nlquery with GNU General Public License v2.0 5 votes vote down vote up
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) 
Example #8
Source File: config_parser.py    From pyhocon with Apache License 2.0 5 votes vote down vote up
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 
Example #9
Source File: gapps.py    From danforth-east with MIT License 5 votes vote down vote up
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 
Example #10
Source File: gapps.py    From danforth-east with MIT License 5 votes vote down vote up
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 [] 
Example #11
Source File: config_parser.py    From trains with Apache License 2.0 5 votes vote down vote up
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 
Example #12
Source File: test_imports.py    From bazarr with GNU General Public License v3.0 5 votes vote down vote up
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) 
Example #13
Source File: date_utils.py    From arches with GNU Affero General Public License v3.0 4 votes vote down vote up
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 
Example #14
Source File: tools.py    From Computable with MIT License 4 votes vote down vote up
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