API Reference

icalendar.cal

Calendar is a dictionary like Python object that can render itself as VCAL files according to RFC 5545.

These are the defined components.

class icalendar.cal.Alarm(*args, **kwargs)[source]
class icalendar.cal.Calendar(*args, **kwargs)[source]

This is the base object for an iCalendar file.

classmethod example(name: str) Calendar[source]

Return the calendar example with the given name.

class icalendar.cal.Component(*args, **kwargs)[source]

Component is the base object for calendar, Event and the other components defined in RFC 5545. Normally you will not use this class directly, but rather one of the subclasses.

add(name, value, parameters=None, encode=1)[source]

Add a property.

Parameters:
  • name (string) – Name of the property.

  • value (Python native type or icalendar property type.) – Value of the property. Either of a basic Python type of any of the icalendar’s own property types.

  • parameters (Dictionary) – Property parameter dictionary for the value. Only available, if encode is set to True.

  • encode (Boolean) – True, if the value should be encoded to one of icalendar’s own property types (Fallback is “vText”) or False, if not.

Returns:

None

add_component(component)[source]

Add a subcomponent to this component.

content_line(name, value, sorted=True)[source]

Returns property as content line.

content_lines(sorted=True)[source]

Converts the Component and subcomponents into content lines.

decoded(name, default=[])[source]

Returns decoded value of property.

classmethod from_ical(st, multiple=False)[source]

Populates the component recursively from a string.

get_inline(name, decode=1)[source]

Returns a list of values (split on comma).

is_empty()[source]

Returns True if Component has no items or subcomponents, else False.

property_items(recursive=True, sorted=True)[source]

Returns properties in this component and subcomponents as: [(name, value), …]

set_inline(name, values, encode=1)[source]

Converts a list of values into comma separated string and sets value to that.

to_ical(sorted=True)[source]
Parameters:

sorted – Whether parameters and properties should be lexicographically sorted.

walk(name=None, select=<function Component.<lambda>>)[source]

Recursively traverses component and subcomponents. Returns sequence of same. If name is passed, only components with name will be returned.

Parameters:
  • name – The name of the component or None such as VEVENT.

  • select – A function that takes the component as first argument and returns True/False.

Returns:

A list of components that match.

Return type:

list[Component]

class icalendar.cal.ComponentFactory(*args, **kwargs)[source]

All components defined in RFC 5545 are registered in this factory class. To get a component you can use it like this.

class icalendar.cal.Event(*args, **kwargs)[source]
property DTEND: date | None

The DTEND property.

The “DTEND” property for a “VEVENT” calendar component specifies the non-inclusive end of the event.

Accepted values: datetime, date. If the attribute has invalid values, we raise InvalidCalendar. If the value is absent, we return None. You can also delete the value with del or by setting it to None.

property DTSTART: date | None

The DTSTART property.

The “DTSTART” property for a “VEVENT” specifies the inclusive start of the event.

Accepted values: datetime, date. If the attribute has invalid values, we raise InvalidCalendar. If the value is absent, we return None. You can also delete the value with del or by setting it to None.

property DURATION: timedelta | None

The DURATION of the component.

The “DTSTART” property for a “VEVENT” specifies the inclusive start of the event. The “DURATION” property in conjunction with the DTSTART property for a “VEVENT” calendar component specifies the non-inclusive end of the event.

If you would like to calculate the duration of an event do not use this. Instead use the difference between DTSTART and DTEND.

property duration: timedelta

The duration of the component.

This duration is calculated from the start and end of the event. You cannot set the duration as it is unclear what happens to start and end.

property end: date | datetime

The end of the component.

Invalid values raise an InvalidCalendar error. If there is no end, we also raise an IncompleteComponent error.

classmethod example(name: str) Event[source]

Return the calendar example with the given name.

property start: date | datetime

The start of the component.

Invalid values raise an InvalidCalendar. If there is no start, we also raise an IncompleteComponent error.

You can get the start, end and duration of an event as follows:

>>> from datetime import datetime
>>> from icalendar import Event
>>> event = Event()
>>> event.start = datetime(2021, 1, 1, 12)
>>> event.end = datetime(2021, 1, 1, 12, 30) # 30 minutes
>>> event.end - event.start  # 1800 seconds == 30 minutes
datetime.timedelta(seconds=1800)
>>> print(event.to_ical())
BEGIN:VEVENT
DTSTART:20210101T120000
DTEND:20210101T123000
END:VEVENT
class icalendar.cal.FreeBusy(*args, **kwargs)[source]
exception icalendar.cal.IncompleteComponent[source]

The component is missing attributes.

The attributes are not required, otherwise this would be an InvalidCalendar. But in order to perform calculations, this attribute is required.

exception icalendar.cal.InvalidCalendar[source]

The calendar given is not valid.

This calendar does not conform with RFC 5545 or breaks other RFCs.

class icalendar.cal.Journal(*args, **kwargs)[source]

A descriptive text at a certain time or associated with a component.

A “VJOURNAL” calendar component is a grouping of component properties that represent one or more descriptive text notes associated with a particular calendar date. The “DTSTART” property is used to specify the calendar date with which the journal entry is associated. Generally, it will have a DATE value data type, but it can also be used to specify a DATE-TIME value data type. Examples of a journal entry include a daily record of a legislative body or a journal entry of individual telephone contacts for the day or an ordered list of accomplishments for the day.

property DTSTART: date | None

The DTSTART property.

The “DTSTART” property for a “VJOURNAL” that specifies the exact date at which the journal entry was made.

Accepted values: datetime, date. If the attribute has invalid values, we raise InvalidCalendar. If the value is absent, we return None. You can also delete the value with del or by setting it to None.

property duration: timedelta

The journal has no duration.

property end: date

The start of the Journal.

The “DTSTART” property is used to specify the calendar date with which the journal entry is associated.

property start: date

The start of the Journal.

The “DTSTART” property is used to specify the calendar date with which the journal entry is associated.

class icalendar.cal.Timezone(*args, **kwargs)[source]
classmethod example(name: str) Calendar[source]

Return the calendar example with the given name.

get_transitions() Tuple[List[datetime], List[Tuple[timedelta, timedelta, str]]][source]

Return a tuple of (transition_times, transition_info)

  • transition_times = [datetime, …]

  • transition_info = [(TZOFFSETTO, dts_offset, tzname)]

to_tz(tzp=TZP('zoneinfo'))[source]

convert this VTIMEZONE component to a timezone object

property tz_name: str

Return the name of the timezone component.

Please note that the names of the timezone are different from this name and may change with winter/summer time.

class icalendar.cal.TimezoneDaylight(*args, **kwargs)[source]
class icalendar.cal.TimezoneStandard(*args, **kwargs)[source]
class icalendar.cal.Todo(*args, **kwargs)[source]
icalendar.cal.get_example(component_directory: str, example_name: str) bytes[source]

Return an example and raise an error if it is absent.

icalendar.caselessdict

class icalendar.caselessdict.CaselessDict(*args, **kwargs)[source]

A dictionary that isn’t case sensitive, and only uses strings as keys. Values retain their case.

copy() a shallow copy of od[source]
get(key, default=None)[source]

Return the value for key if key is in the dictionary, else default.

pop(key[, default]) v, remove specified key and return the corresponding value.[source]

If the key is not found, return the default if given; otherwise, raise a KeyError.

popitem()[source]

Remove and return a (key, value) pair from the dictionary.

Pairs are returned in LIFO order if last is true or FIFO order if false.

setdefault(key, value=None)[source]

Insert key with a value of default if key is not in the dictionary.

Return the value for key if key is in the dictionary, else default.

sorted_items()[source]

Sorts items according to the canonical_order for the derived class. Items not specified in canonical_order will appear at the end.

sorted_keys()[source]

Sorts keys according to the canonical_order for the derived class. Keys not specified in canonical_order will appear at the end.

update([E, ]**F) None.  Update D from mapping/iterable E and F.[source]

If E is present and has a .keys() method, then does: for k in E.keys(): D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]

icalendar.caselessdict.canonsort_items(dict1, canonical_order=None)[source]

Returns a list of items from dict1, sorted by canonical_order.

icalendar.caselessdict.canonsort_keys(keys, canonical_order=None)[source]

Sorts leading keys according to canonical_order. Keys not specified in canonical_order will appear alphabetically at the end.

icalendar.cli

utility program that allows user to preview calendar’s events

icalendar.cli.view(event)[source]

Make a human readable summary of an iCalendar file.

Returns str:

Human readable summary.

icalendar.parser

This module parses and generates contentlines as defined in RFC 5545 (iCalendar), but will probably work for other MIME types with similar syntax. Eg. RFC 2426 (vCard)

It is stupid in the sense that it treats the content purely as strings. No type conversion is attempted.

class icalendar.parser.Contentline(value, strict=False, encoding='utf-8')[source]

A content line is basically a string that can be folded and parsed into parts.

classmethod from_ical(ical, strict=False)[source]

Unfold the content lines in an iCalendar into long content lines.

classmethod from_parts(name, params, values, sorted=True)[source]

Turn a parts into a content line.

parts()[source]

Split the content line up into (name, parameters, values) parts.

to_ical()[source]

Long content lines are folded so they are less than 75 characters wide.

class icalendar.parser.Contentlines(iterable=(), /)[source]

I assume that iCalendar files generally are a few kilobytes in size. Then this should be efficient. for Huge files, an iterator should probably be used instead.

classmethod from_ical(st)[source]

Parses a string into content lines.

to_ical()[source]

Simply join self.

class icalendar.parser.Parameters(*args, **kwargs)[source]

Parser and generator of Property parameter strings. It knows nothing of datatypes. Its main concern is textual structure.

classmethod from_ical(st, strict=False)[source]

Parses the parameter format from ical text format.

params()[source]

In RFC 5545 keys are called parameters, so this is to be consitent with the naming conventions.

icalendar.parser.dquote(val)[source]

Enclose parameter values containing [,;:] in double quotes.

icalendar.parser.escape_char(text)[source]

Format value according to iCalendar TEXT escaping rules.

icalendar.parser.foldline(line, limit=75, fold_sep='\r\n ')[source]

Make a string folded as defined in RFC5545 Lines of text SHOULD NOT be longer than 75 octets, excluding the line break. Long content lines SHOULD be split into a multiple line representations using a line “folding” technique. That is, a long line can be split between any two characters by inserting a CRLF immediately followed by a single linear white-space character (i.e., SPACE or HTAB).

icalendar.parser.param_value(value)[source]

Returns a parameter value.

icalendar.parser.q_join(lst, sep=',')[source]

Joins a list on sep, quoting strings with QUOTABLE chars.

icalendar.parser.q_split(st, sep=',', maxsplit=-1)[source]

Splits a string on char, taking double (q)uotes into considderation.

icalendar.parser_tools

icalendar.parser_tools.data_encode(data: str | bytes | dict | list, encoding='utf-8') bytes[source]

Encode all datastructures to the given encoding. Currently unicode strings, dicts and lists are supported.

icalendar.parser_tools.from_unicode(value: str | bytes, encoding='utf-8') bytes[source]

Converts a value to bytes, even if it already is bytes :param value: The value to convert :param encoding: The encoding to use in the conversion :return: The bytes representation of the value

icalendar.parser_tools.to_unicode(value: str | bytes, encoding='utf-8-sig') str[source]

Converts a value to unicode, even if it is already a unicode string.

icalendar.prop

This module contains the parser/generators (or coders/encoders if you prefer) for the classes/datatypes that are used in iCalendar:


# This module defines these property value data types and property parameters

4.2 Defined property parameters are:

ALTREP, CN, CUTYPE, DELEGATED-FROM, DELEGATED-TO, DIR, ENCODING, FMTTYPE, FBTYPE, LANGUAGE, MEMBER, PARTSTAT, RANGE, RELATED, RELTYPE, ROLE, RSVP, SENT-BY, TZID, VALUE

4.3 Defined value data types are:

BINARY, BOOLEAN, CAL-ADDRESS, DATE, DATE-TIME, DURATION, FLOAT, INTEGER, PERIOD, RECUR, TEXT, TIME, URI, UTC-OFFSET


iCalendar properties have values. The values are strongly typed. This module defines these types, calling val.to_ical() on them will render them as defined in rfc5545.

If you pass any of these classes a Python primitive, you will have an object that can render itself as iCalendar formatted date.

Property Value Data Types start with a ‘v’. they all have an to_ical() and from_ical() method. The to_ical() method generates a text string in the iCalendar format. The from_ical() method can parse this format and return a primitive Python datatype. So it should always be true that:

x == vDataType.from_ical(VDataType(x).to_ical())

These types are mainly used for parsing and file generation. But you can set them directly.

class icalendar.prop.TimeBase[source]

Make classes with a datetime/date comparable.

class icalendar.prop.TypesFactory(*args, **kwargs)[source]

All Value types defined in RFC 5545 are registered in this factory class.

The value and parameter names don’t overlap. So one factory is enough for both kinds.

for_property(name)[source]

Returns a the default type for a property or parameter

from_ical(name, value)[source]

Decodes a named property or parameter value from an icalendar encoded string to a primitive python type.

to_ical(name, value)[source]

Encodes a named value from a primitive python type to an icalendar encoded string.

icalendar.prop.tzid_from_dt(dt: datetime) str | None[source]

Retrieve the timezone id from the datetime object.

class icalendar.prop.vBinary(obj)[source]

Binary property values are base 64 encoded.

class icalendar.prop.vBoolean(*args, **kwargs)[source]

Returns specific string according to state.

class icalendar.prop.vCalAddress(value, encoding='utf-8')[source]

This just returns an unquoted string.

class icalendar.prop.vDDDLists(dt_list)[source]

A list of vDDDTypes values.

class icalendar.prop.vDDDTypes(dt)[source]

A combined Datetime, Date or Duration parser/generator. Their format cannot be confused, and often values can be of either types. So this is practical.

class icalendar.prop.vDate(dt)[source]

Render and generates iCalendar date format.

class icalendar.prop.vDatetime(dt)[source]

Render and generates icalendar datetime format.

vDatetime is timezone aware and uses a timezone library. When a vDatetime object is created from an ical string, you can pass a valid timezone identifier. When a vDatetime object is created from a python datetime object, it uses the tzinfo component, if present. Otherwise an timezone-naive object is created. Be aware that there are certain limitations with timezone naive DATE-TIME components in the icalendar standard.

class icalendar.prop.vDuration(td)[source]

Subclass of timedelta that renders itself in the iCalendar DURATION format.

property dt

The time delta for compatibility.

class icalendar.prop.vFloat(*args, **kwargs)[source]

Just a float.

class icalendar.prop.vFrequency(value, encoding='utf-8')[source]

A simple class that catches illegal values.

class icalendar.prop.vGeo(geo)[source]

A special type that is only indirectly defined in the rfc.

class icalendar.prop.vInline(value, encoding='utf-8')[source]

This is an especially dumb class that just holds raw unparsed text and has parameters. Conversion of inline values are handled by the Component class, so no further processing is needed.

class icalendar.prop.vInt(*args, **kwargs)[source]

Just an int.

class icalendar.prop.vMonth(month: str | int)[source]

The number of the month for recurrence.

In RFC 5545, this is just an int. In RFC 7529, this can be followed by L to indicate a leap month.

>>> from icalendar import vMonth
>>> vMonth(1) # first month January
vMonth('1')
>>> vMonth("5L") # leap month in Hebrew calendar
vMonth('5L')
>>> vMonth(1).leap
False
>>> vMonth("5L").leap
True

Definition from RFC:

type-bymonth = element bymonth {
   xsd:positiveInteger |
   xsd:string
}
property leap: bool

Whether this is a leap month.

to_ical() bytes[source]

The ical representation.

class icalendar.prop.vPeriod(per)[source]

A precise period of time.

property dt

Make this cooperate with the other vDDDTypes.

class icalendar.prop.vRecur(*args, **kwargs)[source]

Recurrence definition.

class icalendar.prop.vSkip(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Skip values for RRULE.

These are defined in RFC 7529.

OMIT is the default value.

class icalendar.prop.vText(value, encoding='utf-8')[source]

Simple text.

class icalendar.prop.vTime(*args)[source]

Render and generates iCalendar time format.

class icalendar.prop.vUTCOffset(td)[source]

Renders itself as a utc offset.

class icalendar.prop.vUri(value, encoding='utf-8')[source]

Uniform resource identifier is basically just an unquoted string.

class icalendar.prop.vWeekday(value, encoding='utf-8')[source]

This returns an unquoted weekday abbrevation.

icalendar.tools

class icalendar.tools.UIDGenerator[source]

If you are too lazy to create real uid’s.

static rnd_string(length=16)[source]

Generates a string with random characters of length.

static uid(host_name='example.com', unique='')[source]
Generates a unique id consisting of:

datetime-uniquevalue@host.

Like:

20050105T225746Z-HKtJMqUgdO0jDUwm@example.com