niccokunzmann / python-recurring-ical-events

Python library to calculate recurrence times of events, todos and journals based on icalendar RFC5545
https://pypi.org/project/recurring-ical-events/
GNU Lesser General Public License v3.0
90 stars 20 forks source link

Recurring ICal events for Python

.. image:: https://github.com/niccokunzmann/python-recurring-ical-events/actions/workflows/tests.yml/badge.svg :target: https://github.com/niccokunzmann/python-recurring-ical-events/actions/workflows/tests.yml :alt: GitHub CI build and test status .. image:: https://badge.fury.io/py/recurring-ical-events.svg :target: https://pypi.python.org/pypi/recurring-ical-events :alt: Python Package Version on Pypi .. image:: https://img.shields.io/pypi/dm/recurring-ical-events.svg :target: https://pypi.org/project/recurring-ical-events/#files :alt: Downloads from Pypi .. image:: https://img.shields.io/opencollective/all/open-web-calendar?label=support%20on%20open%20collective :target: https://opencollective.com/open-web-calendar/ :alt: Support on Open Collective .. image:: https://img.shields.io/github/issues/niccokunzmann/python-recurring-ical-events?logo=github&label=issues%20seek%20funding&color=%230062ff :target: https://polar.sh/niccokunzmann/python-recurring-ical-events :alt: issues seek funding

ICal has some complexity to it: Events, TODOs and Journal entries can be repeated, removed from the feed and edited later on. This tool takes care of these circumstances.

Let's put our expertise together and build a tool that can solve this!

.. image:: https://img.shields.io/badge/RFC_2445-deprecated-red :target: https://datatracker.ietf.org/doc/html/rfc2445#section-4.8.5.2 :alt: RFC 2445 is deprecated .. image:: https://img.shields.io/badge/RFC_5545-supported-green :target: https://datatracker.ietf.org/doc/html/rfc5545 :alt: RFC 5545 is supported .. image:: https://img.shields.io/badge/RFC_7529-todo-red :target: https://github.com/niccokunzmann/python-recurring-ical-events/issues/142 :alt: RFC 7529 is not implemented .. image:: https://img.shields.io/badge/RFC_7953-todo-red :target: https://github.com/niccokunzmann/python-recurring-ical-events/issues/143 :alt: RFC 7953 is not implemented

Not included:

Installation

You can install this package using pip.

.. code:: shell

pip install 'recurring-ical-events==3.*'

On Debian/Ubuntu, you use the package manager to install python-recurring-ical-events <https://tracker.debian.org/pkg/python-recurring-ical-events>_.

.. code:: shell

sudo apt-get install python-recurring-ical-events

Support

We accept donations to sustain our work, once or regular. Consider donating money to open-source as everyone benefits.

Example

.. code-block:: python

import icalendar
import recurring_ical_events
import urllib.request

start_date = (2019, 3, 5)
end_date =   (2019, 4, 1)
url = "http://tinyurl.com/y24m3r8f"

ical_string = urllib.request.urlopen(url).read()
calendar = icalendar.Calendar.from_ical(ical_string)
events = recurring_ical_events.of(calendar).between(start_date, end_date)
for event in events:
    start = event["DTSTART"].dt
    duration = event["DTEND"].dt - event["DTSTART"].dt
    print("start {} duration {}".format(start, duration))

Output:

.. code-block:: text

start 2019-03-18 04:00:00+01:00 duration 1:00:00
start 2019-03-20 04:00:00+01:00 duration 1:00:00
start 2019-03-19 04:00:00+01:00 duration 1:00:00
start 2019-03-07 02:00:00+01:00 duration 1:00:00
start 2019-03-08 01:00:00+01:00 duration 2:00:00
start 2019-03-09 03:00:00+01:00 duration 0:30:00
start 2019-03-10 duration 1 day, 0:00:00

Usage

The icalendar <https://pypi.org/project/icalendar/>_ module is responsible for parsing and converting calendars. The recurring_ical_events <https://pypi.org/project/recurring-ical-events/> module uses such a calendar and creates all repetitions of its events within a time span.

To import this module, write

.. code:: Python

import recurring_ical_events

There are several methods you can use to unfold repeating events, such as at(a_time) and between(a_start, an_end).

at(a_date)


You can get all events which take place at a_date. A date can be a year, e.g. 2023, a month of a year e.g. January in 2023 (2023, 1), a day of a certain month e.g. (2023, 1, 1), an hour e.g. (2023, 1, 1, 0), a minute e.g. (2023, 1, 1, 0, 0), or second as well as a datetime.date <https://docs.python.org/3/library/datetime.html#datetime.date> object and datetime.datetime <https://docs.python.org/3/library/datetime.html#datetime.datetime>.

The start and end are inclusive. As an example: if an event is longer than one day it is still included if it takes place at a_date.

.. code:: Python

a_date =  2023   # a year
a_date = (2023,) # a year
a_date = (2023, 1) # January in 2023
a_date = (2023, 1, 1) # the 1st of January in 2023
a_date = "20230101"   # the 1st of January in 2023
a_date = (2023, 1, 1, 0) # the first hour of the year 2023
a_date = (2023, 1, 1, 0, 0) # the first minute in 2023
a_date = datetime.date(2023) # the first day in 2023
a_date = datetime.date(2023, 1, 1) # the first day in 2023
a_date = datetime.datetime.now() # this exact second

events = recurring_ical_events.of(an_icalendar_object).at(a_date)

The resulting events are a list of icalendar events <https://icalendar.readthedocs.io/en/latest/api.html#icalendar.cal.Event>_, see below.

between(start, end)


between(start, end) returns all events happening between a start and an end time. Both arguments can be datetime.datetime, datetime.date, tuples of numbers passed as arguments to datetime.datetime_ or strings in the form of %Y%m%d (yyyymmdd) and %Y%m%dT%H%M%SZ (yyyymmddThhmmssZ). Additionally, the end argument can be a datetime.timedelta to express that the end is relative to the start. For examples of arguments, see at(a_date) above.

.. code:: Python

events = recurring_ical_events.of(an_icalendar_object).between(start, end)

The resulting events are in a list of icalendar events_, see below.

after(earliest_end)


You can retrieve events that happen after a time or date using after(earliest_end). Events that are happening during the earliest_end are included in the iteration.

.. code:: Python

earlierst_end = 2019
for event in recurring_ical_events.of(an_icalendar_object).after(earlierst_end):
    print(event["DTEND"]) # all dates printed are after January 1st 2019

all()


If you wish to iterate over all occurrences of the components, then you can use all(). Since a calendar can define a huge amount of recurring entries, this method generates them and forgets them, reducing memory overhead.

This example shows the first event that takes place in the calendar:

.. code:: Python

query = recurring_ical_events.of(an_icalendar_object)
first_event = next(query.all()) # not all events are generated
print("First event starts at: {first_event}")

count()


You can count occurrences of events and other components using count().

.. code:: Python

number_of_events = recurring_ical_events.of(an_icalendar_object).count()
print(f"{number_of_events} events happen in this calendar.")

number_of_TODOs = recurring_ical_events.of(an_icalendar_object, components=["VTODO"]).count()
print(f"You have {number_of_TODOs} things to do!")

number_of_journal_entries = recurring_ical_events.of(an_icalendar_object, components=["VJOURNAL"]).count()
print(f"There are {number_of_journal_entries} journal entries in the calendar.")

events as list - at() and between()


The result of both between(start, end) and at(a_date) is a list of icalendar events_. By default, all attributes of the event with repetitions are copied, like UID and SUMMARY. However, these attributes may differ from the source event:

Generator - after() and all()


If the resulting components are ordered when after(earliest_end) or all() is used. The result is an iterator that returns the events in order.

.. code:: Python

for event in recurring_ical_events.of(an_icalendar_object).after(datetime.datetime.now()):
    print(event["DTSTART"]) # The start is ordered

Different Components, not just Events


By default the recurring_ical_events only selects events as the name already implies. However, there are different components <https://icalendar.readthedocs.io/en/latest/api.html#icalendar.cal.Component> available in a calendar <https://icalendar.readthedocs.io/en/latest/api.html#icalendar.cal.Calendar>. You can select which components you like to have returned by passing components to the of function:

.. code:: Python

of(a_calendar, components=["VEVENT"])

Here is a template code for choosing the supported types of components:

.. code:: Python

events = recurring_ical_events.of(calendar).between(...) journals = recurring_ical_events.of(calendar, components=["VJOURNAL"]).between(...) todos = recurring_ical_events.of(calendar, components=["VTODO"]).between(...) all = recurring_ical_events.of(calendar, components=["VTODO", "VEVENT", "VJOURNAL"]).between(...)

If a type of component is not listed here, it can be added. Please create an issue for this in the source code repository.

Speed


If you use between() or at() several times, it is faster to re-use the object coming from of().

.. code:: Python

rcalendar = recurring_ical_events.of(an_icalendar_object)
events_of_day_1 = rcalendar.at(day_1)
events_of_day_2 = rcalendar.at(day_2)
events_of_day_3 = rcalendar.at(day_3)
# ...

Skip bad formatted ical events


Some events may be badly formatted and therefore cannot be handled by recurring-ical-events. Passing skip_bad_series=True as of() argument will totally skip theses events.

.. code:: Python

of(a_calendar, skip_bad_series=True)

Version Fixing


If you use this library in your code, you may want to make sure that updates can be received but they do not break your code. The version numbers are handeled this way: a.b.c example: 0.1.12

So, I recommend to version-fix this library to stay with the same a while b and c can change.

Development

Code style


Please install pre-commit <https://pre-commit.com/> before git commit. It will ensure that the code is formatted and linted as expected using ruff <https://docs.astral.sh/ruff/>.

.. code-block:: shell

pre-commit install

Testing


This project's development is driven by tests. Tests assure a consistent interface and less knowledge lost over time. If you like to change the code, tests help that nothing breaks in the future. They are required in that sense. Example code and ics files can be transferred into tests and speed up fixing bugs.

You can view the tests in the test folder <https://github.com/niccokunzmann/python-recurring-ical-events/tree/master/test>. If you have a calendar ICS file for which this library does not generate the desired output, you can add it to the test/calendars folder and write tests for what you expect. If you like, open an issue <https://github.com/niccokunzmann/python-recurring-ical-events/issues> first, e.g. to discuss the changes and how to go about it.

To run the tests, we use tox. tox tests all different Python versions which we want to be compatible to.

.. code-block:: shell

pip3 install tox

To run all the tests:

.. code-block:: shell

tox

To run the tests in a specific Python version:

.. code-block:: shell

tox -e py39

New Releases

To release new versions,

  1. edit the Changelog Section

  2. edit setup.py, the __version__ variable

  3. create a commit and push it

  4. wait for GitHub Actions <https://github.com/niccokunzmann/python-recurring-ical-events/actions>_ to finish the build

  5. run

    .. code-block:: shell

    python3 setup.py tag_and_deploy

  6. notify the issues about their release

Architecture

.. image:: img/architecture.png :alt: Architecture Diagram showing the components interacting

Each icalendar Calendar can contain Events, Journal entries, TODOs and others, called Components. Those entries are grouped by their UID. Such a UID defines a Series of Occurrences that take place at a given time. Since each Component is different, the ComponentAdapter offers a unified interface to interact with them. The Calendar gets filtered and for each UID, a Series can use one or more ComponentAdapters to create Occurrences of what happens in a time span. These Occurrences are used internally and convert to Components for further use.

Changelog

Libraries Used

Related Projects

Media

Nicco Kunzmann talked about this library at the FOSSASIA 2022 Summit:

.. image:: https://niccokunzmann.github.io/ical-talk-fossasia-2022/youtube.png :target: https://youtu.be/8l3opDdg92I?t=10369 :alt: Talk about this library at the FOSSASIA 2022 Summit

Research