icalendar.cal.calendar module#
RFC 5545 iCalendar component.
- class icalendar.cal.calendar.Calendar(*args, **kwargs)[source]#
Bases:
ComponentThe "VCALENDAR" object is a collection of calendar information. This information can include a variety of components, such as "VEVENT", "VTODO", "VJOURNAL", "VFREEBUSY", "VTIMEZONE", or any other type of calendar component.
Example
Create a new Calendar:
>>> from icalendar import Calendar >>> calendar = Calendar.new(name="My Calendar") >>> print(calendar.calendar_name) My Calendar
Get the example Calendar:
>>> from icalendar import Calendar >>> calendar = Calendar.example() >>> print(calendar.calendar_name) Holidays >>> len(calendar.events) 3
Set keys to upper for initial dict.
- add_missing_timezones(first_date=datetime.date(1970, 1, 1), last_date=datetime.date(2038, 1, 1))[source]#
Add all missing VTIMEZONE components.
This adds all the timezone components that are required. VTIMEZONE components are inserted at the beginning of the calendar to ensure they appear before other components that reference them.
Note
Timezones that are not known will not be added.
- Parameters:
>>> from icalendar import Calendar, Event >>> from datetime import datetime >>> from zoneinfo import ZoneInfo >>> calendar = Calendar() >>> event = Event() >>> calendar.add_component(event) >>> event.start = datetime(1990, 10, 11, 12, tzinfo=ZoneInfo("Europe/Berlin")) >>> calendar.timezones [] >>> calendar.add_missing_timezones() >>> calendar.timezones[0].tz_name 'Europe/Berlin' >>> calendar.get_missing_tzids() # check that all are added set()
- property availabilities: list[Availability]#
All
Availabilitycomponents in the calendar.This is a shortcut to get all availabilities. Modifications do not change the calendar. Use
Component.add_component.
- property calendar_name: str | None#
The display name of this calendar, per RFC 7986 Section 5.1.
Implements both the
NAMEproperty from RFC 7986 Section 5.1 and the widely usedX-WR-CALNAMEextension for broader client compatibility.Multiple language variants can be stored by setting this property more than once, each with a different
LANGUAGEparameter value.Example
Set the name of the calendar.
>>> from icalendar import Calendar >>> calendar = Calendar() >>> calendar.calendar_name = "My Calendar" >>> print(calendar.to_ical().decode()) BEGIN:VCALENDAR NAME:My Calendar X-WR-CALNAME:My Calendar END:VCALENDAR
- property calscale: str#
The calendar scale for date and time values in this iCalendar object.
This property is defined in RFC 5545 Section 3.7.1. The only value currently defined is
"GREGORIAN"(the default). When this property is absent, Gregorian is assumed.Per RFC 7529, non-Gregorian calendar systems are expressed via
RRULEtransformations rather than a differentCALSCALEvalue. However, icalendar currently implements only the parsing of this value, not a transformation.Example
>>> from icalendar import Calendar >>> cal = Calendar() >>> cal.calscale 'GREGORIAN'
- canonical_order = ('VERSION', 'PRODID', 'CALSCALE', 'METHOD', 'URL', 'DESCRIPTION', 'X-WR-CALDESC', 'NAME', 'X-WR-CALNAME')#
- property categories: list[str]#
This property defines the categories for a component.
The categories property is used to specify categories or subtypes of the calendar component. The categories are useful to search for a calendar component of a particular type and category.
Within the calendar components, specify categories as a list of strings. You can get, set, and delete categories for a component.
This property can be used in icalendar through its Python attributes of:
The categories property for
AvailableandAvailabilitycomplies with RFC 7953 Section 3.1, forEvent,Journal, andTodowith RFC 5545 Section 3.8.1.2, and forCalendarwith RFC 7986 Section 5.6.Note
At present, icalendar doesn't take the LANGUAGE parameter as defined in RFC 5545 Section 3.2.10 into account.
Example
Create an event, add categories to it, print its ical representation, append another category, and finally compare the result against its expected value.
>>> from icalendar import Event >>> event = Event() >>> event.categories = ["Work", "Meeting"] >>> print(event.to_ical()) BEGIN:VEVENT CATEGORIES:Work,Meeting END:VEVENT >>> event.categories.append("Lecture") >>> event.categories == ["Work", "Meeting", "Lecture"] True
See also
- property color: str#
A CSS3 color name or value used to visually distinguish this calendar, per RFC 7986 Section 5.9.
Implements both
COLORfrom RFC 7986 Section 5.9 andX-APPLE-CALENDAR-COLOR. The value is a case-insensitive CSS3 color name, for example,"turquoise", or a hex code, for example,"#ffffff", drawn from the CSS3 color specification.Since RFC 7986, individual
VEVENT,VTODO, andVJOURNALsubcomponents may also carry their own color.Example
>>> from icalendar import Calendar >>> calendar = Calendar() >>> calendar.color = "black" >>> print(calendar.to_ical().decode()) BEGIN:VCALENDAR COLOR:black END:VCALENDAR
- property description: str | None#
A description of the calendar's content.
Implements both
DESCRIPTIONfrom RFC 5545 Section 3.8.1.5 and RFC 7986 Section 5.2 andX-WR-CALDESCfor broader calendar client compatibility.Multiple language variants can be stored by setting this property more than once with different
LANGUAGEparameter values.Example
Add a description to a calendar.
>>> from icalendar import Calendar >>> calendar = Calendar() >>> calendar.description = "This is a calendar" >>> print(calendar.to_ical().decode()) BEGIN:VCALENDAR DESCRIPTION:This is a calendar X-WR-CALDESC:This is a calendar END:VCALENDAR
- property events: list[Event]#
All event components in the calendar.
This is a shortcut to get all events. Modifications do not change the calendar. Use
Component.add_component.>>> from icalendar import Calendar >>> calendar = Calendar.example() >>> event = calendar.events[0] >>> event.start datetime.date(2022, 1, 1) >>> print(event["SUMMARY"]) New Year's Day
- classmethod example(name='example')[source]#
Return the calendar example with the given name.
Example
>>> from icalendar import Calendar >>> print(Calendar.example().to_ical().decode()) BEGIN:VCALENDAR VERSION:2.0 PRODID:PyCalendar/icalendar CALSCALE:GREGORIAN METHOD:PUBLISH X-WR-CALNAME:Holidays X-WR-TIMEZONE:Etc/GMT BEGIN:VEVENT SUMMARY:New Year's Day DTSTART:20220101 DTEND:20220101 DTSTAMP:20221108T080105Z UID:636a0cc1dbd5a1667894465@icalendar SEQUENCE:0 DESCRIPTION:Happy New Year! STATUS:CONFIRMED TRANSP:TRANSPARENT END:VEVENT BEGIN:VEVENT SUMMARY:Orthodox Christmas DTSTART:20220107 DTEND:20220107 UID:636a0cc1dbfd91667894465@icalendar SEQUENCE:0 DESCRIPTION:It is Christmas again! LOCATION:Russia STATUS:CONFIRMED TRANSP:TRANSPARENT END:VEVENT BEGIN:VEVENT SUMMARY:International Women's Day DTSTART:20220308 DTEND:20220308 UID:636a0cc1dc0f11667894465@icalendar SEQUENCE:0 DESCRIPTION:May the feminine be honoured! STATUS:CONFIRMED TRANSP:TRANSPARENT END:VEVENT END:VCALENDAR
- Return type:
- property freebusy: list[FreeBusy]#
All FreeBusy components in the calendar.
This is a shortcut to get all FreeBusy. Modifications do not change the calendar. Use
Component.add_component.
- classmethod from_ical(st, multiple=False)[source]#
Parse iCalendar data into calendar instances.
- Overloads:
- Parameters:
- Returns:
Calendar or list of calendars.
- get_missing_tzids()[source]#
The set of missing timezone component tzids.
To create a RFC 5545 compatible calendar, all of these timezones should be added.
UTC is excluded: per RFC 5545 Section 3.2.19, UTC datetimes use the
Zsuffix and never require a VTIMEZONE component.
- get_used_tzids()[source]#
The set of TZIDs in use.
This goes through the whole calendar to find all occurrences of timezone information like the TZID parameter in all attributes.
>>> from icalendar import Calendar >>> calendar = Calendar.example("timezone_rdate") >>> calendar.get_used_tzids() {'posix/Europe/Vaduz'}
Even if you use UTC, this will not show up.
- property images: list[Image]#
IMAGE specifies an image associated with the calendar or a calendar component.
- Description:
This property specifies an image for an iCalendar object or a calendar component via a URI or directly with inline data that can be used by calendar user agents when presenting the calendar data to a user. Multiple properties MAY be used to specify alternative sets of images with, for example, varying media subtypes, resolutions, or sizes. When multiple properties are present, calendar user agents SHOULD display only one of them, picking one that provides the most appropriate image quality, or display none. The "DISPLAY" parameter is used to indicate the intended display mode for the image. The "ALTREP" parameter, defined in RFC 5545, can be used to provide a "clickable" image where the URI in the parameter value can be "launched" by a click on the image in the calendar user agent.
- Conformance:
This property can be specified multiple times in an iCalendar object or in "VEVENT", "VTODO", or "VJOURNAL" calendar components.
Note
At the present moment, this property is read-only. If you require a setter, please open an issue or a pull request.
- property journals: list[Journal]#
All journal components in the calendar.
This is a shortcut to get all journals. Modifications do not change the calendar. Use
Component.add_component.
- property method: str#
The iTIP scheduling method associated with this calendar object, per RFC 5545 Section 3.7.2.
When present,
METHODindicates that this object is part of a scheduling transaction, such as a meeting invitation or cancellation. Scheduling methods are defined by RFC 5546 Section 1.4 (iTIP), with values such as"REQUEST","REPLY","CANCEL", and"PUBLISH".When used inside a MIME message, this value must match the
methodparameter of theContent-Typeheader. If absent, the calendar is treated as a plain data snapshot with no scheduling semantics.Example
>>> from icalendar import Calendar >>> cal = Calendar() >>> cal.method = "REQUEST" >>> str(cal.method) 'REQUEST'
- multiple: ClassVar[tuple[()]] = ('CATEGORIES', 'DESCRIPTION', 'NAME')#
These properties may occur more than once.
- name: ClassVar[str | None] = 'VCALENDAR'#
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(calscale=None, categories=(), color=None, concepts=None, description=None, language=None, last_modified=None, links=None, method=None, name=None, organization=None, prodid=None, refresh_interval=None, refids=None, related_to=None, source=None, subcomponents=None, uid=None, url=None, version='2.0')[source]#
Create a new Calendar.
This creates a new Calendar in accordance with RFC 5545 and RFC 7986.
- Parameters:
categories (
Sequence[str]) – Thecategoriesof the calendar.concepts (
list[vUri|str] |str|vUri|None) – Theconceptsof the calendar.description (
str|None) – Thedescriptionof the calendar.language (
str|None) – The language for the calendar. Used to generate localized prodid.last_modified (
date|datetime|None) – Thelast_modifiedof the calendar.links (
str|vUri|vUid|vXmlReference|list[str|vUri|vUid|vXmlReference] |None) – Thelinksof the calendar.name (
str|None) – Thecalendar_nameof the calendar.organization (
str|None) – The organization name. Used to generate prodid if not provided.prodid (
str|None) – Theprodidof the component. IfNoneandorganizationis provided, generates a prodid in the format of "-//organization//name//language". IfNoneandorganizationis not provided, sets it toDEFAULT_PRODID.refresh_interval (
timedelta|None) – Therefresh_intervalof the calendar.related_to (
str|vText|vUri|vUid|list[str|vText|vUri|vUid] |None) –related_toof the calendar.subcomponents (
Iterable[Component] |None) – The subcomponents of the calendar.uid (
str|UUID|None) – Theuidof the calendar. If None, this is set to a newuuid.uuid4().
- Return type:
- Returns:
- Raises:
InvalidCalendar – If the content is not valid according to RFC 5545.
Warning
As time progresses, we will be stricter with the validation.
- property prodid: str#
The product identifier for the software that created this iCalendar object.
This property is defined in RFC 5545 Section 3.7.3. It's required exactly once per iCalendar object.
The value should be a globally unique string. The conventional format is a Formal Public Identifier (FPI), for example,
-//My Company//My Product//EN, but any unique string is acceptable.Example
Set a custom product identifier on a new calendar.
>>> from icalendar import Calendar >>> cal = Calendar() >>> cal.prodid = "-//MyApp//MyCalendar//EN" >>> str(cal.prodid) '-//MyApp//MyCalendar//EN'
See also
- property refresh_interval: timedelta | None#
A suggested minimum polling interval for fetching updates to this calendar, per RFC 7986 Section 5.7.
Calendar clients should not poll more frequently than this interval. The value must be a positive duration.
- Returns:
A
timedelta, orNonewhen not set.- Raises:
ValueError – When setting a non-positive (zero or negative) duration.
TypeError – When setting a value that is not a
timedeltaorNone.
Example
>>> from datetime import timedelta >>> from icalendar import Calendar >>> cal = Calendar() >>> cal.refresh_interval = timedelta(hours=1) >>> cal.refresh_interval datetime.timedelta(seconds=3600)
- singletons: ClassVar[tuple[()]] = ('PRODID', 'VERSION', 'CALSCALE', 'METHOD', 'COLOR')#
These properties must appear only once.
- property source: str#
A URI from where calendar data can be refreshed.
- Description:
This property identifies a location where a client can retrieve updated data for the calendar. Clients SHOULD honor any specified "REFRESH-INTERVAL" value when periodically retrieving data. Note that this property differs from the "URL" property in that "URL" is meant to provide an alternative representation of the calendar data rather than the original location of the data.
- Conformance:
This property can be specified once in an iCalendar object.
Example
The following is an example of this property:
SOURCE;VALUE=URI:https://example.com/holidays.ics
- property timezones: list[Timezone]#
Return the timezones components in this calendar.
>>> from icalendar import Calendar >>> calendar = Calendar.example("pacific_fiji") >>> [timezone.tz_name for timezone in calendar.timezones] ['custom_Pacific/Fiji']
Note
This is a read-only property.
- property todos: list[Todo]#
All todo components in the calendar.
This is a shortcut to get all todos. Modifications do not change the calendar. Use
Component.add_component.
- property uid: str#
UID specifies the persistent, globally unique identifier for a component.
It's generated automatically when calling
Event.new,Todo.new, orJournal.new.To manually set, use
uuid.uuid4()to generate new values, and the class'suidproperty. When set, the value must be an RFC 5545 iana-token consisting of only ASCII letters, digits, and hyphens, and be shorter than 255 octets, as required by RFC 7986 Section 5.3. To clear the value, set it to""orNone. Values that do not conform raiseInvalidCalendar.- Returns:
The value of the UID property as a string, or
""if no value is set.
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
Set a new UUID4 as the UID (recommended):
>>> from icalendar import Event >>> from uuid import uuid4 >>> event = Event() >>> event.uid = uuid4() >>> event.uid vText(b'...')
Setting a valid token preserves its casing, while an invalid value raises an error:
>>> event.uid = "AbC-123" # a valid token, casing is preserved >>> print(event.uid) AbC-123 >>> event.uid = "a b" Traceback (most recent call last): ... icalendar.error.InvalidCalendar: UID must be an RFC 5545 iana-token, got 'a b'
- property url: str#
A Uniform Resource Locator (URL) associated with a calendar component.
This property specifies a URI where a more dynamic rendition of the calendar information can be found. It is commonly used to reference related resources or provide additional information about the component.
According to RFC 5545 Section 3.8.4.6, this property can be specified once in "VEVENT", "VTODO", "VJOURNAL", or "VFREEBUSY" calendar components. Since RFC 7986 Section 5.5, this property can also be defined on a "VCALENDAR". RFC 7953 Section 3.1 allows this property in "VAVAILABILITY" components.
This property may be used in a calendar component to convey a location where a more dynamic rendition of the calendar information can be found. If both the URL property and Content-Location MIME header are specified, they MUST point to the same resource.
This differs from the SOURCE property, which identifies where calendar data can be refreshed from, whereas URL provides an alternative representation of the current calendar data.
Examples
Set a URL for an event that references additional information:
>>> from icalendar import Event >>> event = Event() >>> event.add('url', 'http://example.com/events/meeting-2025') >>> print(event.to_ical().decode('utf-8')) BEGIN:VEVENT URL:http://example.com/events/meeting-2025 END:VEVENT
Set a URL for a calendar:
>>> from icalendar import Calendar >>> calendar = Calendar() >>> calendar.add('url', 'http://example.com/pub/calendars/jsmith/mytime.ics') >>> print(calendar.to_ical().decode('utf-8')) BEGIN:VCALENDAR URL:http://example.com/pub/calendars/jsmith/mytime.ics END:VCALENDAR
See also
sourcefor specifying from where calendar data can be refreshed.icalendar implementations:
- validate()[source]#
Validate that the calendar has required properties and components.
This method can be called explicitly to validate a calendar before output.
- Raises:
IncompleteComponent – If the calendar lacks required properties or components.
- property version: str#
The iCalendar specification version required to interpret this object.
This property is defined in RFC 5545 Section 3.7.4. It's required exactly once per calendar object. The value
"2.0"indicates RFC 5545 compliance, which is the default used by this library. A range such as"1.0;2.0"may indicate minimum and maximum supported versions.Example
>>> from icalendar import Calendar >>> cal = Calendar() >>> cal.version = "2.0" >>> str(cal.version) '2.0'
See also