icalendar.cal.component module#
The base for RFC 5545 components.
- class icalendar.cal.component.Component(*args, **kwargs)[source]#
Bases:
CaselessDictBase 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,
createdfalls back toDTSTAMP.This property is applicable to
VEVENT,VTODO, andVJOURNALcomponents. 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'))
See also
- 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, andVFREEBUSYcomponents.When the calendar object carries a
METHODproperty, such as for scheduling, this value is the creation time of this particular revision. Without aMETHODproperty, it's equivalent toLAST_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'))
See also
- 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_modifiedfalls back toDTSTAMP.This property is applicable to
VEVENT,VTODO,VJOURNAL, andVTIMEZONEcomponents. 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'))
See also
- property XML: PropertyListView#
This property embeds XML elements into a component.
You can assign XML text, an
Element, anElementAdapter, a list of these, orNoneto this property. The values becomevXmlvalues. AvTextvalue is not converted, so it is written as text in xCal. XML with the value type BINARY is avBinary. AssigningNoneor 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']
- 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
nameisDTSTAMP,CREATED, orLAST-MODIFIEDandvalueis adatetime, 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) –Trueif the value should be encoded to one of icalendar's own property types (fallback isvText);Falseto store the value as-is. Default isTrue.parameters (
dict[str,str] |Parameters) – Property parameter dictionary for the value. Only consulted whenencodeisTrue.
- Return type:
- Returns:
None
Example
>>> from icalendar import Event >>> event = Event() >>> event.add("summary", "Team sync") >>> event["summary"] vText(b'Team sync')
- 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, andVFREEBUSYcomponents as well as on theirSTANDARDandDAYLIGHTsub-components. For availability components, it is defined in RFC 7953, and may appear multiple times onVAVAILABILITYandVAVAILABLE.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.'
- copy(recursive=False)[source]#
Copy the component.
- Parameters:
recursive (
bool) – IfTrue, this creates copies of the component, its subcomponents, and all its properties. IfFalse, this only creates a shallow copy of the component.- Return type:
- 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
CREATEDis an optional property, this returnsDTSTAMPifCREATEDis 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.
- errors: list[tuple[str | None, str]]#
The errors that occurred while parsing this component.
Each entry is a
(name, message)tuple.nameis the name of the property whose value could not be parsed, orNoneif a whole content line was unparseable and therefore skipped.messageis the description of the problem.Errors are recorded instead of raised only when the component sets
ignore_exceptionstoTrue, asEventdoes, or when the property is an unregisteredX-property. A property with an unparseable value is kept as avBrokenvalue, soto_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")]
See also
- 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 aspathlib.Path.multiple (
bool) – IfTrue, returns list. IfFalse, 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:
JCalParsingError – If the jCal provided is invalid.
JSONDecodeError – If the provided string is not valid JSON.
- Return type:
This reverses
to_json()andto_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:
- Returns:
The parsed component.
- Raises:
XCalParsingError – If the provided XML does not conform with RFC 6321.
TypeError – If
xcalis not one of the valid types.xml.etree.ElementTree.ParseError – If the provided data is not valid XML.
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
- 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:
- is_thunderbird()[source]#
Whether this component has attributes that indicate that Mozilla Thunderbird created it.
- Return type:
- property last_modified: datetime#
Datetime when the information associated with the component was last revised.
Since
LAST_MODIFIEDis an optional property, this returnsDTSTAMPifLAST_MODIFIEDis not set.
- 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:
comments (
list[str] |str|None) – Thecommentsof the component.concepts (
list[vUri|str] |str|vUri|None) – Theconceptsof the component.last_modified (
date|None) – Thelast_modifiedof the component.links (
str|vUri|vUid|vXmlReference|list[str|vUri|vUid|vXmlReference] |None) – Thelinksof the component.refids (
list[str] |str|None) – Therefidsof the component.related_to (
str|vText|vUri|vUid|list[str|vText|vUri|vUid] |None) – Therelated_toof the component.subcomponents (
Iterable[Component] |None) – The subcomponents of the component.
- Raises:
InvalidCalendar – If the content is not valid according to RFC 5545.
- Return type:
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:
- property_items(recursive=True, sorted=True)[source]#
Returns properties in this component and subcomponents as a list.
The list contains
(name, value)tuples.
- 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, ordel) 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.
- classmethod register(component_class)[source]#
Register a custom component class.
- Parameters:
component_class (
type[Component]) – Component subclass to register. Must have anameattribute.- Raises:
ValueError – If
component_classhas nonameattribute.ValueError – If a component with this name is already registered.
- Return type:
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)
- 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, ifencodeis truthy. Then they are joined to form the property value.encode (
bool) –Trueif each value in values should be encoded to one of icalendar's own property types with a fallback tovText, elseFalse. Default isTrue.
- property stamp: datetime | None#
Datetime stamp of this component, as a
datetimein UTC.This is the lowercase property counterpart to, and accessor for,
DTSTAMP.- Setter accepts:
- to_jcal()[source]#
Convert this component to a jCal object.
- Return type:
- 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:
- 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:
- Returns:
Noneif an argument is passed.bytesif called with no arguments.
- Raises:
TypeError – If
destinationis neither an XMLElementnor a file-like object, or ifindentis neither an integer nor a string.InvalidCalendar – If an XML property cannot be written to xCal. See
vXml.to_xcal().
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:
- 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
uuidmodule to generate new UUIDs.- Compatibility:
For Alarms,
X-ALARMUIDis 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
- 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
nameandselect. The name match is case-insensitive, so"vevent"findsVEVENTcomponents.- Parameters:
- Returns:
- The matching components, starting with this one
if it matches.
- Return type: