Python dateutil.rrule.rrulestr() Examples

The following are 14 code examples of dateutil.rrule.rrulestr(). 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.rrule , or try the search function .
Example #1
Source File: test_imports.py    From plugin.video.emby with GNU General Public License v3.0 7 votes vote down vote up
def testRRuleAll(self):
        from dateutil.rrule import rrule
        from dateutil.rrule import rruleset
        from dateutil.rrule import rrulestr
        from dateutil.rrule import YEARLY, MONTHLY, WEEKLY, DAILY
        from dateutil.rrule import HOURLY, MINUTELY, SECONDLY
        from dateutil.rrule import MO, TU, WE, TH, FR, SA, SU

        rr_all = (rrule, rruleset, rrulestr,
                  YEARLY, MONTHLY, WEEKLY, DAILY,
                  HOURLY, MINUTELY, SECONDLY,
                  MO, TU, WE, TH, FR, SA, SU)

        for var in rr_all:
            self.assertIsNot(var, None)

        # In the public interface but not in all
        from dateutil.rrule import weekday
        self.assertIsNot(weekday, None) 
Example #2
Source File: utils.py    From karrot-backend with GNU Affero General Public License v3.0 6 votes vote down vote up
def rrule_between_dates_in_local_time(rule, dtstart, tz, period_start, period_duration):
    rule = rrulestr(rule)

    # using local time zone to avoid daylight saving time errors
    period_start_local = period_start.astimezone(tz).replace(tzinfo=None)
    dtstart_local = dtstart.astimezone(tz).replace(tzinfo=None)

    until = None
    # UNTIL needs to be in local time zone as well
    if rule._until is not None:
        until = rule._until.astimezone(tz).replace(tzinfo=None)

    rule = rule.replace(
        dtstart=dtstart_local,
        until=until,
    ).between(
        period_start_local,
        period_start_local + period_duration,
    )
    return [tz.localize(date) for date in rule] 
Example #3
Source File: test_activity_series_api.py    From karrot-backend with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_set_end_date_with_users_have_joined_activity(self):
        self.client.force_login(user=self.member)
        self.series.activities.last().add_participant(self.member)
        # change rule
        url = '/api/activity-series/{}/'.format(self.series.id)
        rule = rrulestr(self.series.rule, dtstart=self.now) \
            .replace(until=self.now)
        response = self.client.patch(url, {
            'rule': str(rule),
        })
        self.assertEqual(response.status_code, status.HTTP_200_OK, response.data)
        self.assertEqual(response.data['rule'], str(rule))

        # compare resulting activities
        url = '/api/activities/'
        response = self.get_results(url, {'series': self.series.id, 'date_min': self.now})
        self.assertEqual(response.status_code, status.HTTP_200_OK, response.data)
        self.assertEqual(len(response.data), 1, response.data) 
Example #4
Source File: test_imports.py    From bazarr with GNU General Public License v3.0 6 votes vote down vote up
def testRRuleAll(self):
        from dateutil.rrule import rrule
        from dateutil.rrule import rruleset
        from dateutil.rrule import rrulestr
        from dateutil.rrule import YEARLY, MONTHLY, WEEKLY, DAILY
        from dateutil.rrule import HOURLY, MINUTELY, SECONDLY
        from dateutil.rrule import MO, TU, WE, TH, FR, SA, SU

        rr_all = (rrule, rruleset, rrulestr,
                  YEARLY, MONTHLY, WEEKLY, DAILY,
                  HOURLY, MINUTELY, SECONDLY,
                  MO, TU, WE, TH, FR, SA, SU)

        for var in rr_all:
            self.assertIsNot(var, None)

        # In the public interface but not in all
        from dateutil.rrule import weekday
        self.assertIsNot(weekday, None) 
Example #5
Source File: recurrence.py    From ls.joyous with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, *args, **kwargs):
        super().__init__()
        arg0 = args[0] if len(args) else None
        if isinstance(arg0, str):
            self.rule = rrulestr(arg0, **kwargs)
            if not isinstance(self.rule, rrule):
                raise ValueError("Only support simple RRules for now")
        elif isinstance(arg0, Recurrence):
            self.rule = arg0.rule
        elif isinstance(arg0, rrule):
            self.rule = arg0
        else:
            self.rule = rrule(*args, **kwargs)

    # expose all rrule properties
    #: How often the recurrence repeats. (0,1,2,3) 
Example #6
Source File: models.py    From karrot-backend with GNU Affero General Public License v3.0 5 votes vote down vote up
def delete(self, **kwargs):
        self.rule = str(rrulestr(self.rule).replace(dtstart=self.start_date, until=timezone.now()))
        self.update_activities()
        return super().delete() 
Example #7
Source File: ical.py    From autosuspend with GNU General Public License v2.0 5 votes vote down vote up
def _expand_rrule_all_day(
    rrule: str, start: date, exclusions: Iterable, start_at: datetime, end_at: datetime
) -> Iterable[date]:
    """Expand an rrule for all-day events.

    To my mind, these events cannot have changes, just exclusions, because
    changes only affect the time, which doesn't exist for all-day events.
    """

    rules = rruleset()
    rules.rrule(rrulestr(rrule, dtstart=start, ignoretz=True))

    # add exclusions
    if exclusions:
        for xdate in exclusions:
            rules.exdate(datetime.combine(xdate.dts[0].dt, datetime.min.time()))

    dates = []
    # reduce start and end to datetimes without timezone that just represent a
    # date at midnight.
    for candidate in rules.between(
        datetime.combine(start_at.date(), datetime.min.time()),
        datetime.combine(end_at.date(), datetime.min.time()),
        inc=True,
    ):
        dates.append(candidate.date())
    return dates 
Example #8
Source File: main.py    From hogar with MIT License 5 votes vote down vote up
def _set_recurring_reminder (r, orig_message):
    '''
        Set Recurring Reminder

        Record a recurring reminder in the database to be sent.

        #TODO: Implement this

        --
        @param  r:dict              The parsed message from the user
        @param  orig_message:str    The original message received

        @return str
    '''

    logger.debug('Storing reminder for {id}'.format(
        id = orig_message['chat']['id']
    ))

    RemindRecurring.create(
        orig_message = json.dumps(orig_message),
        rrules = r['parsed_time'],
        next_run = rrulestr(r['parsed_time'],
                            dtstart = datetime.datetime.now()).after(datetime.datetime.now()),
        message = r['message']
    )

    return 
Example #9
Source File: calendar_time.py    From karbor with Apache License 2.0 5 votes vote down vote up
def _get_rrule_obj(vevent, dtstart):
        rrules = vevent.get('RRULE')
        rrule_list = rrules if isinstance(rrules, list) else [rrules]
        rrule_str = os.linesep.join(recur.to_ical().decode("utf-8")
                                    for recur in rrule_list)
        return rrule.rrulestr(rrule_str, dtstart=dtstart, cache=False) 
Example #10
Source File: test_recurrence.py    From sync-engine with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_rrule_to_json():
    # Generate more test cases!
    # http://jakubroztocil.github.io/rrule/
    r = 'RRULE:FREQ=WEEKLY;UNTIL=20140918T203000Z;BYDAY=TH'
    r = rrulestr(r, dtstart=None)
    j = rrule_to_json(r)
    assert j.get('freq') == 'WEEKLY'
    assert j.get('byweekday') == 'TH'

    r = 'FREQ=HOURLY;COUNT=30;WKST=MO;BYMONTH=1;BYMINUTE=42;BYSECOND=24'
    r = rrulestr(r, dtstart=None)
    j = rrule_to_json(r)
    assert j.get('until') is None
    assert j.get('byminute') is 42 
Example #11
Source File: test_recurrence.py    From sync-engine with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_rrule_to_json():
    # Generate more test cases!
    # http://jakubroztocil.github.io/rrule/
    r = 'RRULE:FREQ=WEEKLY;UNTIL=20140918T203000Z;BYDAY=TH'
    r = rrulestr(r, dtstart=None)
    j = rrule_to_json(r)
    assert j.get('freq') == 'WEEKLY'
    assert j.get('byweekday') == 'TH'

    r = 'FREQ=HOURLY;COUNT=30;WKST=MO;BYMONTH=1;BYMINUTE=42;BYSECOND=24'
    r = rrulestr(r, dtstart=None)
    j = rrule_to_json(r)
    assert j.get('until') is None
    assert j.get('byminute') is 42 
Example #12
Source File: ical.py    From autosuspend with GNU General Public License v2.0 4 votes vote down vote up
def _expand_rrule(
    rrule: str,
    start: datetime,
    instance_duration: timedelta,
    exclusions: Iterable,
    changes: Iterable[icalendar.cal.Event],
    start_at: datetime,
    end_at: datetime,
) -> Sequence[datetime]:

    # unify everything to a single timezone and then strip it to handle DST
    # changes correctly
    orig_tz = start.tzinfo
    start = start.replace(tzinfo=None)
    start_at = start_at.astimezone(orig_tz).replace(tzinfo=None)
    end_at = end_at.astimezone(orig_tz).replace(tzinfo=None)

    rules = rruleset()
    first_rule = rrulestr(rrule, dtstart=start, ignoretz=True)

    # apply the same timezone logic for the until part of the rule after
    # parsing it.
    if first_rule._until:
        first_rule._until = (
            pytz.utc.localize(first_rule._until)
            .astimezone(orig_tz)
            .replace(tzinfo=None)
        )

    rules.rrule(first_rule)

    # add exclusions
    if exclusions:
        for xdate in exclusions:
            try:
                # also in this case, unify and strip the timezone
                rules.exdate(xdate.dts[0].dt.astimezone(orig_tz).replace(tzinfo=None))
            except AttributeError:
                pass

    # add events that were changed
    for change in changes:
        # same timezone mangling applies here
        rules.exdate(
            change.get("recurrence-id").dt.astimezone(orig_tz).replace(tzinfo=None)
        )

    # expand the rrule
    dates = []
    for candidate in rules.between(start_at - instance_duration, end_at, inc=True):
        localized = orig_tz.localize(candidate)  # type: ignore
        dates.append(localized)
    return dates 
Example #13
Source File: icalparser.py    From icalevents with MIT License 4 votes vote down vote up
def parse_rrule(component, tz=UTC):
    """
    Extract a dateutil.rrule object from an icalendar component. Also includes
    the component's dtstart and exdate properties. The rdate and exrule
    properties are not yet supported.

    :param component: icalendar component
    :param tz: timezone for DST handling
    :return: extracted rrule or rruleset
    """
    if component.get('rrule'):
        # component['rrule'] can be both a scalar and a list
        rrules = component['rrule']
        if not isinstance(rrules, list):
            rrules = [rrules]

        # If dtstart is a datetime, make sure it's in a timezone.
        rdtstart = component['dtstart'].dt
        if type(rdtstart) is datetime:
            rdtstart = normalize(rdtstart, tz=tz)

        # Parse the rrules, might return a rruleset instance, instead of rrule
        rule = rrulestr('\n'.join(x.to_ical().decode() for x in rrules),
                        dtstart=rdtstart)

        if component.get('exdate'):
            # Make sure, to work with a rruleset
            if isinstance(rule, rrule):
                rules = rruleset()
                rules.rrule(rule)
                rule = rules

            # Add exdates to the rruleset
            for exd in extract_exdates(component):
                rule.exdate(exd)

        # TODO: What about rdates and exrules?

    # You really want an rrule for a component without rrule? Here you are.
    else:
        rule = rruleset()
        rule.rdate(normalize(component['dtstart'].dt, tz=tz))

    return rule 
Example #14
Source File: Reminder.py    From hogar with MIT License 4 votes vote down vote up
def run_remind_recurring ():
    '''
        Run Remind Recurring

        Find and send all of the recurring reminders that are due

        --
        @return void
    '''

    logger.debug('Running Remind Recurring Job')

    try:

        # Get reminders have have not been marked as completed, as well as
        # have their next_run date ready or not set
        for reminder in RemindRecurring.select().where(RemindRecurring.sent == 0,
                                                       ((RemindRecurring.next_run <= datetime.now()) | (
                                                           RemindRecurring.next_run >> None))):

            # If we know the next_run date, send the message. If
            # we dont know the next_run, this will be skipped
            # and only the next_run determined
            if reminder.next_run is not None:
                logger.debug('Sending recurring reminder message with id {id}'.format(
                    id = reminder.id
                ))

                # Send the actual reminder
                Telegram.send_message(
                    _get_sender_information(reminder.orig_message),
                    'text',
                    reminder.message)

            # Lets parse the rrules and update the next_run time for
            # a message. We will use python-dateutil to help with
            # determinig the next run based on the parsed RRULE
            # relative from now.
            next_run = rrulestr(reminder.rrules,
                                dtstart = datetime.now()).after(datetime.now())

            # If there is no next run, consider the
            # schedule complete and mark it as
            # sent
            if not next_run:
                reminder.sent = 1
                reminder.save()

                continue

            # Save the next run
            reminder.next_run = next_run
            reminder.save()

    except Exception, e:

        print traceback.format_exc()