icalendar.cal.component module#

The base for RFC 5545 components.

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

Bases: CaselessDict

Base class for calendar components.

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.

On initialization, this class sets its keys to upper case.

property CREATED: datetime | None#

The UTC datetime when this calendar component was first created, per RFC 5545 Section 3.8.7.1.

This property records when the calendar user agent originally stored the component. This property is optional. When it's absent, created falls back to DTSTAMP.

This property is applicable to VEVENT, VTODO, and VJOURNAL components. The value is always in UTC.

Example

>>> from datetime import timezone, datetime
>>> from icalendar import Event
>>> event = Event()
>>> event.CREATED = datetime(2024, 1, 1, 8, 0, 0, tzinfo=timezone.utc)
>>> event.CREATED
datetime.datetime(2024, 1, 1, 8, 0, tzinfo=ZoneInfo(key='UTC'))
property DTSTAMP: datetime | None#

The UTC datetime stamp recording when this component instance was created or last revised.

This property is defined in RFC 5545 Section 3.8.7.2. It's required in VEVENT, VTODO, VJOURNAL, and VFREEBUSY components.

When the calendar object carries a METHOD property, such as for scheduling, this value is the creation time of this particular revision. Without a METHOD property, it's equivalent to LAST_MODIFIED.

The value is always in UTC. It's also accessible as stamp.

Example

>>> from datetime import timezone, datetime
>>> from icalendar import Event
>>> event = Event()
>>> event.DTSTAMP = datetime(2024, 6, 1, 12, 0, 0, tzinfo=timezone.utc)
>>> event.DTSTAMP
datetime.datetime(2024, 6, 1, 12, 0, tzinfo=ZoneInfo(key='UTC'))
property LAST_MODIFIED: datetime | None#

The UTC datetime when this component's information was last revised, per RFC 5545 Section 3.8.7.3.

It's analogous to a file's modification timestamp. This property is optional. When it's absent, last_modified falls back to DTSTAMP.

This property is applicable to VEVENT, VTODO, VJOURNAL, and VTIMEZONE components. The value is always in UTC.

Example

>>> from datetime import timezone, datetime
>>> from icalendar import Event
>>> event = Event()
>>> event.LAST_MODIFIED = datetime(2024, 6, 1, 9, 0, 0, tzinfo=timezone.utc)
>>> event.LAST_MODIFIED
datetime.datetime(2024, 6, 1, 9, 0, tzinfo=ZoneInfo(key='UTC'))
property XML: PropertyListView#

This property embeds XML elements into a component.

You can assign XML text, an Element, an ElementAdapter, a list of these, or None to this property. The values become vXml values. A vText value is not converted, so it is written as text in xCal. XML with the value type BINARY is a vBinary. Assigning None or an empty list removes all XML values, as does deleting the property.

The XML property is defined in RFC 6321 Section 4.2. It can be specified multiple times in any component. Its value is an XML element in a namespace other than the iCalendar namespace. In xCal, the element is part of the properties of the component, see RFC 6321 Section 4.1.

Note

To change the values, assign a new list or use add(). Changing the returned list does not always change the component.

Example

Add XML to an event and get the XML elements:

>>> from icalendar import Event
>>> event = Event()
>>> event.XML = '<a xmlns="http://example.com/ns">text</a>'
>>> print(event.to_ical().decode())
BEGIN:VEVENT
XML:<a xmlns="http://example.com/ns">text</a>
END:VEVENT
>>> [xml.element.tag for xml in event.XML]
['{http://example.com/ns}a']
Setter accepts:

list[str] | str | None

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

Add a property to this component.

If the property already exists, the new value is appended so the property carries a list of values rather than replacing the previous one. When name is DTSTAMP, CREATED, or LAST-MODIFIED and value is a datetime, the value is converted to UTC as the RFC requires.

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

  • value – Required. Value of the property. Either a basic Python type or any of icalendar's own property types.

  • encode (bool) – True if the value should be encoded to one of icalendar's own property types (fallback is vText); False to store the value as-is. Default is True.

  • parameters (dict[str, str] | Parameters) – Property parameter dictionary for the value. Only consulted when encode is True.

Return type:

None

Returns:

None

Example

>>> from icalendar import Event
>>> event = Event()
>>> event.add("summary", "Team sync")
>>> event["summary"]
vText(b'Team sync')
add_component(component)[source]#

Add a subcomponent to this component.

Return type:

None

property comments: list[str]#

Specifies a comment to the calendar user.

This property holds free-text notes attached to a component; calendar clients display it but never act on it. It is defined in RFC 5545 Section 3.8.1.4 and may appear multiple times on VEVENT, VTODO, VJOURNAL, and VFREEBUSY components as well as on their STANDARD and DAYLIGHT sub-components. For availability components, it is defined in RFC 7953, and may appear multiple times on VAVAILABILITY and VAVAILABLE.

You can get, set, append, and delete comments on a component. The value is a list of strings; each string is one comment.

Example

Add two comments to an event and then read them back.

>>> from icalendar import Event
>>> event = Event()
>>> event.add("COMMENT", "Moved from the planning board.")
>>> event.add("COMMENT", "Confirmed by phone.")
>>> [str(c) for c in event.comments]
['Moved from the planning board.', 'Confirmed by phone.']
>>> str(event.comments[0])
'Moved from the planning board.'
Setter accepts:

str | Sequence[str] | None

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.

copy(recursive=False)[source]#

Copy the component.

Parameters:

recursive (bool) – If True, this creates copies of the component, its subcomponents, and all its properties. If False, this only creates a shallow copy of the component.

Return type:

Self

Returns:

A copy of the component.

Examples

Create a shallow copy of a component:

>>> from icalendar import Event
>>> event = Event.new(description="Event to be copied")
>>> event_copy = event.copy()
>>> str(event_copy.description)
'Event to be copied'

Shallow copies lose their subcomponents:

>>> from icalendar import Calendar
>>> calendar = Calendar.example()
>>> len(calendar.subcomponents)
3
>>> calendar_copy = calendar.copy()
>>> len(calendar_copy.subcomponents)
0

A recursive copy also copies all the subcomponents:

>>> full_calendar_copy = calendar.copy(recursive=True)
>>> len(full_calendar_copy.subcomponents)
3
>>> full_calendar_copy.events[0] == calendar.events[0]
True
>>> full_calendar_copy.events[0] is calendar.events[0]
False
property created: datetime#

Datetime when the information associated with the component was created.

Since CREATED is an optional property, this returns DTSTAMP if CREATED is not set.

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

Return the decoded value of a property.

A component maps keys to icalendar property value types. This function returns values compatible with native Python types.

Parameters:
  • name (str) – Required. The name of the property.

  • default (Any) – The value to return if the property is not present. If omitted, a KeyError is raised.

Return type:

Any

Returns:

The decoded value of the property, or default if the property is not present.

errors: list[tuple[str | None, str]]#

The errors that occurred while parsing this component.

Each entry is a (name, message) tuple. name is the name of the property whose value could not be parsed, or None if a whole content line was unparseable and therefore skipped. message is the description of the problem.

Errors are recorded instead of raised only when the component sets ignore_exceptions to True, as Event does, or when the property is an unregistered X- property. A property with an unparseable value is kept as a vBroken value, so to_ical() writes it back unchanged.

Errors are recorded per component: this list stays empty when only a subcomponent is affected. Use walk() to collect all of them.

Example

>>> from icalendar import Calendar, Event
>>> event = Calendar.example("broken_dtstart").events[0]
>>> event.errors
[('DTSTART', "Expected datetime, date, or time. Got: 'INVALID-DATE'")]

A content line that cannot be split into a name, parameters, and a value is recorded without a property name:

>>> Event.example("issue_104_mark_events_broken").errors
[(None, "Content line could not be parsed into parts: 'X': Invalid content line")]
exclusive: ClassVar[tuple[()]] = ()#

These properties are mutually exclusive.

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

Parse iCalendar data into component instances.

Overloads:

Handles standard and custom components (X-*, IANA-registered).

Parameters:
  • st (str | bytes | Path) – iCalendar data as bytes or string, or a path to an iCalendar file as pathlib.Path.

  • multiple (bool) – If True, returns list. If False, returns single component.

Returns:

Component or list of components

See also

Custom components for examples of parsing custom components

classmethod from_jcal(jcal)[source]#

Create a component from a jCal list.

Parameters:

jcal (str | list) – jCal list or JSON string according to RFC 7265.

Raises:
Return type:

Component

This reverses to_json() and to_jcal().

The following code parses an example from RFC 7265:

>>> from icalendar import Component
>>> jcal = ["vcalendar",
...   [
...     ["calscale", {}, "text", "GREGORIAN"],
...     ["prodid", {}, "text", "-//Example Inc.//Example Calendar//EN"],
...     ["version", {}, "text", "2.0"]
...   ],
...   [
...     ["vevent",
...       [
...         ["dtstamp", {}, "date-time", "2008-02-05T19:12:24Z"],
...         ["dtstart", {}, "date", "2008-10-06"],
...         ["summary", {}, "text", "Planning meeting"],
...         ["uid", {}, "text", "4088E990AD89CB3DBB484909"]
...       ],
...       []
...     ]
...   ]
... ]
>>> calendar = Component.from_jcal(jcal)
>>> print(calendar.name)
VCALENDAR
>>> print(calendar.prodid)
-//Example Inc.//Example Calendar//EN
>>> event = calendar.events[0]
>>> print(event.summary)
Planning meeting
classmethod from_xcal(xcal)[source]#

Parse xCal according to RFC 6321.

Parameters:

xcal (Element | bytes | Path | BinaryIO) – The xCal element or data to parse.

Return type:

list[Self]

Returns:

The parsed component.

Raises:

Example

Parse an xCal object from a bytes object in XML format.

>>> from icalendar import Calendar
>>> xml = b'''<?xml version="1.0" encoding="utf-8"?>
... <icalendar xmlns="urn:ietf:params:xml:ns:icalendar-2.0">
...     <vcalendar>
...         <properties>
...             <prodid>
...                 <text>-//Example Inc.//Example Client//EN</text>
...             </prodid>
...             <version>
...                 <text>2.0</text>
...             </version>
...         </properties>
...     </vcalendar>
... </icalendar>
... '''
>>> cal = Calendar.from_xcal(xml)[0]
>>> cal.prodid == '-//Example Inc.//Example Client//EN'
True
get(key, default=None)[source]#

Get property value with default.

Return type:

Any

classmethod get_component_class(name)[source]#

Return a component with this name.

Parameters:

name (str) – Required. The name of the component, such as VCALENDAR.

Return type:

type[Component]

Returns:

The component class registered for name.

get_inline(name, decode=1)[source]#

Returns a list of values (split on comma).

ignore_exceptions: ClassVar[bool] = False#

Whether or not to ignore exceptions when parsing.

If True, and this component can't be parsed, then it will silently ignore it, rather than let the exception propagate upwards.

inclusive: ClassVar[tuple[str] | tuple[tuple[str, str]]] = ()#

These properties are inclusive.

In other words, if the first property in the tuple occurs, then the second one must also occur.

Example

('duration', 'repeat')
is_empty()[source]#

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

Return type:

bool

is_lazy()[source]#

This component is fully parsed.

Return type:

bool

is_thunderbird()[source]#

Whether this component has attributes that indicate that Mozilla Thunderbird created it.

Return type:

bool

property last_modified: datetime#

Datetime when the information associated with the component was last revised.

Since LAST_MODIFIED is an optional property, this returns DTSTAMP if LAST_MODIFIED is not set.

multiple: ClassVar[tuple[()]] = ()#

These properties may occur more than once.

name: ClassVar[str | None] = None#

The name of the component.

This is defined in each component class.

Example

>>> from icalendar import Calendar
>>> cal = Calendar.new()
>>> cal.name
'VCALENDAR'
classmethod new(created=None, comments=None, concepts=None, last_modified=None, links=None, refids=None, related_to=None, stamp=None, subcomponents=None)[source]#

Create a new component.

Parameters:
Raises:

InvalidCalendar – If the content is not valid according to RFC 5545.

Return type:

Self

Warning

As time progresses, we will be stricter with the validation.

parse()[source]#

Return the fully parsed component.

For non-lazy components, this returns self. For lazy components, this parses the component and returns the result.

Return type:

Self

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

Returns properties in this component and subcomponents as a list.

The list contains (name, value) tuples.

Return type:

list[tuple[str, object]]

property refids: PropertyListView#

REFID

Purpose:

REFID acts as a key for associated iCalendar entities.

Conformance:

Since RFC 9253, this property can be specified zero or more times in any iCalendar component.

Description:

The value of this property is free-form text that creates an identifier for associated components. All components that use the same REFID value are associated through that value and can be located or retrieved as a group. For example, all of the events in a travel itinerary would have the same REFID value, so as to be grouped together.

Examples

The following is an example of this property.

REFID:itinerary-2014-11-17

Use a REFID to associate several VTODOs:

>>> from icalendar import Todo
>>> todo_1 = Todo.new(
...     summary="turn off stove",
...     refids=["travel", "alps"]
... )
>>> todo_2 = Todo.new(
...     summary="pack backpack",
...     refids=["travel", "alps"]
... )
>>> todo_1.refids == todo_2.refids
True

Note

When you assign a list to this property, the returned list is the same object stored in the component. Modifying it (append(), extend(), remove(), item assignment, or del) changes what the component stores.

However, if you assign a single string value to this property, the returned list is a temporary copy, and changes to this list don't affect the component.

Setter accepts:

list[str] | str | None

classmethod register(component_class)[source]#

Register a custom component class.

Parameters:

component_class (type[Component]) – Component subclass to register. Must have a name attribute.

Raises:
  • ValueError – If component_class has no name attribute.

  • ValueError – If a component with this name is already registered.

Return type:

None

Examples

Create a custom icalendar component with the name X-EXAMPLE:

>>> from icalendar import Component
>>> class XExample(Component):
...     name = "X-EXAMPLE"
...     def custom_method(self):
...         return "custom"
>>> Component.register(XExample)
required: ClassVar[tuple[()]] = ()#

These properties are required.

set_inline(name, values, encode=True)[source]#

Convert a list of values into a comma-separated string and set the property value to it.

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

  • values (Sequence[str]) – Required. Values of the properties. The properties are encoded, if encode is truthy. Then they are joined to form the property value.

  • encode (bool) – True if each value in values should be encoded to one of icalendar's own property types with a fallback to vText, else False. Default is True.

singletons: ClassVar[tuple[()]] = ()#

These properties must appear only once.

property stamp: datetime | None#

Datetime stamp of this component, as a datetime in UTC.

This is the lowercase property counterpart to, and accessor for, DTSTAMP.

Setter accepts:

datetime

subcomponents: list[Component]#

All subcomponents of this component.

to_ical(sorted=True)[source]#

Convert component to iCalendar format.

Parameters:

sorted (bool) – Whether parameters and properties should be lexicographically sorted. Default is True.

Return type:

bytes

Returns:

The iCalendar representation of the component.

to_jcal()[source]#

Convert this component to a jCal object.

Return type:

list

Returns:

jCal object

Raises:

ValueError – If a component does not have a name.

See also to_json.

In this example, we create a simple VEVENT component and convert it to jCal:

>>> from icalendar import Event
>>> from datetime import date
>>> from pprint import pprint
>>> event = Event.new(summary="My Event", start=date(2025, 11, 22))
>>> pprint(event.to_jcal())
['vevent',
 [['summary', {}, 'text', 'My Event'],
  ['dtstart', {}, 'date', '2025-11-22'],
  ['dtstamp', {}, 'date-time', '2025-05-17T08:06:12Z'],
  ['uid', {}, 'text', 'd755cef5-2311-46ed-a0e1-6733c9e15c63']],
 []]
to_json(indent=None)[source]#

Return this component as a jCal JSON string.

Parameters:

indent (int | str | None) – If a non-negative integer or string is provided, then JSON will be pretty-printed with that indent level.

Return type:

str

Returns:

JSON string

Raises:

ValueError – If a component does not have a name.

See also to_jcal.

to_xcal(destination=None, *, indent=None)[source]#

The xCal representation of this component according to RFC 6321.

Overloads:
Parameters:
  • destination (Element | IO[bytes] | None) – The iCalendar stream or a file.

  • indent (int | str | None) – The indentation for pretty printing the XML.

Returns:

  • None if an argument is passed.

  • bytes if called with no arguments.

Raises:

Example

This example shows how to convert a new calendar to XML:

>>> from icalendar import Calendar
>>> cal = Calendar.new()
>>> print(cal.to_xcal(indent=2).decode())
<?xml version="1.0" encoding="UTF-8"?>
<icalendar xmlns="urn:ietf:params:xml:ns:icalendar-2.0">
  <vcalendar>
    <properties>
      <version>
        <text>2.0</text>
      </version>
      <prodid>
        <text>-//PyCalendar//icalendar//7.0.0//EN</text>
      </prodid>
      <uid>
        <text>d755cef5-2311-46ed-a0e1-6733c9e15c63</text>
      </uid>
    </properties>
  </vcalendar>
</icalendar>
to_xcal_element(element, /)[source]#

Add the xCal representation of this component according to RFC 6321.

Return type:

None

types_factory: ClassVar[TypesFactory] = {'ADR': <class 'icalendar.prop.adr.vAdr'>, 'BINARY': <class 'icalendar.prop.binary.vBinary'>, 'BOOLEAN': <class 'icalendar.prop.boolean.vBoolean'>, 'CAL-ADDRESS': <class 'icalendar.prop.cal_address.vCalAddress'>, 'CATEGORIES': <class 'icalendar.prop.categories.vCategory'>, 'DATE': <class 'icalendar.prop.dt.types.vDDDTypes'>, 'DATE-TIME': <class 'icalendar.prop.dt.types.vDDDTypes'>, 'DATE-TIME-LIST': <class 'icalendar.prop.dt.list.vDDDLists'>, 'DURATION': <class 'icalendar.prop.dt.types.vDDDTypes'>, 'FLOAT': <class 'icalendar.prop.float.vFloat'>, 'GEO': <class 'icalendar.prop.geo.vGeo'>, 'INLINE': <class 'icalendar.prop.inline.vInline'>, 'INTEGER': <class 'icalendar.prop.integer.vInt'>, 'N': <class 'icalendar.prop.n.vN'>, 'ORG': <class 'icalendar.prop.org.vOrg'>, 'PERIOD': <class 'icalendar.prop.dt.period.vPeriod'>, 'RECUR': <class 'icalendar.prop.recur.recur.vRecur'>, 'REQUEST-STATUS-TEXT': <class 'icalendar.prop.request_status.vRequestStatus'>, 'TEXT': <class 'icalendar.prop.text.vText'>, 'TIME': <class 'icalendar.prop.dt.time.vTime'>, 'UID': <class 'icalendar.prop.uid.vUid'>, 'UNKNOWN': <class 'icalendar.prop.unknown.vUnknown'>, 'URI': <class 'icalendar.prop.uri.vUri'>, 'UTC-OFFSET': <class 'icalendar.prop.dt.utc_offset.vUTCOffset'>, 'X-BROKEN': <class 'icalendar.prop.broken.vBroken'>, 'XML-REFERENCE': <class 'icalendar.prop.xml_reference.vXmlReference'>, 'XML-TEXT': <class 'icalendar.prop.xml.vXml'>}#

The factory class to parse and wrap properties.

property uid: str#

UID specifies the persistent, globally unique identifier for a component.

We recommend using uuid.uuid4() to generate new values.

Returns:

The value of the UID property as a string or "" if no value is set.

Description:

The "UID" itself MUST be a globally unique identifier. The generator of the identifier MUST guarantee that the identifier is unique.

This is the method for correlating scheduling messages with the referenced "VEVENT", "VTODO", or "VJOURNAL" calendar component. The full range of calendar components specified by a recurrence set is referenced by referring to just the "UID" property value corresponding to the calendar component. The "RECURRENCE-ID" property allows the reference to an individual instance within the recurrence set.

This property is an important method for group-scheduling applications to match requests with later replies, modifications, or deletion requests. Calendaring and scheduling applications MUST generate this property in "VEVENT", "VTODO", and "VJOURNAL" calendar components to assure interoperability with other group- scheduling applications. This identifier is created by the calendar system that generates an iCalendar object.

Implementations MUST be able to receive and persist values of at least 255 octets for this property, but they MUST NOT truncate values in the middle of a UTF-8 multi-octet sequence.

RFC 7986 states that UID can be used, for example, to identify duplicate calendar streams that a client may have been given access to. It can be used in conjunction with the "LAST-MODIFIED" property also specified on the "VCALENDAR" object to identify the most recent version of a calendar.

Conformance:

RFC 5545 states that the "UID" property can be specified on "VEVENT", "VTODO", and "VJOURNAL" calendar components. RFC 7986 modifies the definition of the "UID" property to allow it to be defined in an iCalendar object. RFC 9074 adds a "UID" property to "VALARM" components to allow a unique identifier to be specified. The value of this property can then be used to refer uniquely to the "VALARM" component.

This property can be specified once only.

Security:

RFC 7986 states that UID values MUST NOT include any data that might identify a user, host, domain, or any other security- or privacy-sensitive information. It is RECOMMENDED that calendar user agents now generate "UID" values that are hex-encoded random Universally Unique Identifier (UUID) values as defined in Sections 4.4 and 4.5 of RFC 4122. You can use the uuid module to generate new UUIDs.

Compatibility:

For Alarms, X-ALARMUID is also considered.

Examples

The following is an example of such a property value: 5FC53010-1267-4F8E-BC28-1D7AE55A7C99.

Set the UID of a calendar:

>>> from icalendar import Calendar
>>> from uuid import uuid4
>>> calendar = Calendar()
>>> calendar.uid = uuid4()
>>> print(calendar.to_ical())
BEGIN:VCALENDAR
UID:d755cef5-2311-46ed-a0e1-6733c9e15c63
END:VCALENDAR
Setter accepts:

str | None

walk(name=None, select=None)[source]#

Return this component and its subcomponents that match the filters.

A component is kept only if it matches both name and select. The name match is case-insensitive, so "vevent" finds VEVENT components.

Parameters:
  • name (str | None) – Component name to keep, such as "VEVENT"; None keeps every name.

  • select (Callable[[Component], bool] | None) – Function that takes a component as its first argument and returns True to keep it, or False otherwise. Default is None, which keeps every component.

Returns:

The matching components, starting with this one

if it matches.

Return type:

list[Component]

with_uid(uid)[source]#

Return a list of components with the given UID.

Parameters:

uid (str) – The UID of the component.

Returns:

List of components with the given UID.

Return type:

list[Component]