# 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)

class icalendar.cal.Calendar(*args, **kwargs)

  This is the base object for an iCalendar file.

  classmethod example(name: str) → Calendar

    Return the calendar example with the given name.

class icalendar.cal.Component(*args, **kwargs)

  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)

    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)

    Add a subcomponent to this component.

  content_line(name, value, sorted=True)

    Returns property as content line.

  content_lines(sorted=True)

    Converts the Component and subcomponents into content lines.

  decoded(name, default=[])

    Returns decoded value of property.

  classmethod from_ical(st, multiple=False)

    Populates the component recursively from a string.

  get_inline(name, decode=1)

    Returns a list of values (split on comma).

  is_empty()

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

  property_items(recursive=True, sorted=True)

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

  set_inline(name, values, encode=1)

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

  to_ical(sorted=True)
    Parameters:

      sorted – Whether parameters and properties should be lexicographically sorted.

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

    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)

  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)
  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

    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)

exception icalendar.cal.IncompleteComponent

  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

  The calendar given is not valid.

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

class icalendar.cal.Journal(*args, **kwargs)

  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)
  classmethod example(name: str) → Calendar

    Return the calendar example with the given name.

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

    Return a tuple of (transition_times, transition_info)

    - transition_times = [datetime, …]

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

  to_tz(tzp=TZP('zoneinfo'))

    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)

class icalendar.cal.TimezoneStandard(*args, **kwargs)

class icalendar.cal.Todo(*args, **kwargs)

icalendar.cal.get_example(component_directory: str, example_name: str) → bytes

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

## icalendar.caselessdict

class icalendar.caselessdict.CaselessDict(*args, **kwargs)

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

  copy() → a shallow copy of od
  get(key, default=None)

    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.

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

  popitem()

    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)

    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()

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

  sorted_keys()

    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.

    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)

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

icalendar.caselessdict.canonsort_keys(keys, canonical_order=None)

  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)

  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')

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

  classmethod from_ical(ical, strict=False)

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

  classmethod from_parts(name, params, values, sorted=True)

    Turn a parts into a content line.

  parts()

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

  to_ical()

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

class icalendar.parser.Contentlines(iterable=(), /)

  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)

    Parses a string into content lines.

  to_ical()

    Simply join self.

class icalendar.parser.Parameters(*args, **kwargs)

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

  classmethod from_ical(st, strict=False)

    Parses the parameter format from ical text format.

  params()

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

icalendar.parser.dquote(val)

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

icalendar.parser.escape_char(text)

  Format value according to iCalendar TEXT escaping rules.

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

  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)

  Returns a parameter value.

icalendar.parser.q_join(lst, sep=',')

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

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

  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

  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

  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

  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

  Make classes with a datetime/date comparable.

class icalendar.prop.TypesFactory(*args, **kwargs)

  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)

    Returns a the default type for a property or parameter

  from_ical(name, value)

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

  to_ical(name, value)

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

icalendar.prop.tzid_from_dt(dt: datetime) → str | None

  Retrieve the timezone id from the datetime object.

class icalendar.prop.vBinary(obj)

  Binary property values are base 64 encoded.

class icalendar.prop.vBoolean(*args, **kwargs)

  Returns specific string according to state.

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

  This just returns an unquoted string.

class icalendar.prop.vDDDLists(dt_list)

  A list of vDDDTypes values.

class icalendar.prop.vDDDTypes(dt)

  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)

  Render and generates iCalendar date format.

class icalendar.prop.vDatetime(dt)

  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)

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

  property dt

    The time delta for compatibility.

class icalendar.prop.vFloat(*args, **kwargs)

  Just a float.

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

  A simple class that catches illegal values.

class icalendar.prop.vGeo(geo)

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

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

  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)

  Just an int.

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

  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

    The ical representation.

class icalendar.prop.vPeriod(per)

  A precise period of time.

  property dt

    Make this cooperate with the other vDDDTypes.

class icalendar.prop.vRecur(*args, **kwargs)

  Recurrence definition.

class icalendar.prop.vSkip(*values)

  Skip values for RRULE.

  These are defined in RFC 7529.

  OMIT is the default value.

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

  Simple text.

class icalendar.prop.vTime(*args)

  Render and generates iCalendar time format.

class icalendar.prop.vUTCOffset(td)

  Renders itself as a utc offset.

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

  Uniform resource identifier is basically just an unquoted string.

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

  This returns an unquoted weekday abbrevation.

## icalendar.tools

class icalendar.tools.UIDGenerator

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

  static rnd_string(length=16)

    Generates a string with random characters of length.

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

      datetime-uniquevalue@host.

    Like:

      20050105T225746Z-HKtJMqUgdO0jDUwm@example.com