class Calendar
A Calendar class representing a Microsoft 365 calendar container for events, which can be a user calendar or a Microsoft 365 group's default calendar.
/tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/outlook/calendar/calendar.py
24 - 242
complex
Purpose
This class provides a comprehensive interface for managing Microsoft 365 calendars, including querying calendar permissions, retrieving free/busy schedules, accessing events, managing calendar properties (color, name, permissions), and working with extended properties. It inherits from Entity and integrates with the Microsoft Graph API to perform calendar operations such as checking sharing roles, getting availability schedules, and managing calendar permissions and events.
Source Code
class Calendar(Entity):
"""
A calendar which is a container for events. It can be a calendar for a user, or the default calendar
of a Microsoft 365 group.
"""
def __repr__(self):
return self.name or self.id or self.entity_type_name
def allowed_calendar_sharing_roles(self, user):
"""
:param str user: User identifier or principal name
"""
params = {"user": user}
return_type = ClientResult(self.context, StringCollection())
qry = FunctionQuery(self, "allowedCalendarSharingRoles", params, return_type)
self.context.add_query(qry)
return return_type
def get_schedule(
self, schedules, start_time, end_time, availability_view_interval=30
):
"""
Get the free/busy availability information for a collection of users, distributions lists, or resources
(rooms or equipment) for a specified time period.
:param datetime.datetime end_time: The date, time, and time zone that the period ends.
:param int availability_view_interval: Represents the duration of a time slot in an availabilityView
in the response. The default is 30 minutes, minimum is 5, maximum is 1440. Optional.
:param datetime.datetime start_time: The date, time, and time zone that the period starts.
:param list[str] schedules: A collection of SMTP addresses of users, distribution lists,
or resources to get availability information for.
"""
payload = {
"schedules": schedules,
"startTime": DateTimeTimeZone.parse(start_time),
"endTime": DateTimeTimeZone.parse(end_time),
"availabilityViewInterval": availability_view_interval,
}
return_type = ClientResult(
self.context, ClientValueCollection(ScheduleInformation)
)
qry = ServiceOperationQuery(
self, "getSchedule", None, payload, None, return_type
)
self.context.add_query(qry)
return return_type
@property
def allowed_online_meeting_providers(self):
"""
Represent the online meeting service providers that can be used to create online meetings in this calendar.
Possible values are: unknown, skypeForBusiness, skypeForConsumer, teamsForBusiness.
"""
return self.properties.get("allowedOnlineMeetingProviders", StringCollection())
@property
def can_edit(self):
# type: () -> Optional[bool]
"""
true if the user can write to the calendar, false otherwise.
This property is true for the user who created the calendar.
This property is also true for a user who has been shared a calendar and granted write access.
"""
return self.properties.get("canEdit", None)
@property
def can_share(self):
# type: () -> Optional[bool]
"""
true if the user has the permission to share the calendar, false otherwise.
Only the user who created the calendar can share it.
"""
return self.properties.get("canShare", None)
@property
def can_view_private_items(self):
# type: () -> Optional[bool]
"""
true if the user can read calendar items that have been marked private, false otherwise.
"""
return self.properties.get("canViewPrivateItems", None)
@property
def change_key(self):
# type: () -> Optional[str]
"""
Identifies the version of the calendar object. Every time the calendar is changed, changeKey changes as well.
This allows Exchange to apply changes to the correct version of the object.
"""
return self.properties.get("changeKey", None)
@property
def color(self):
# type: () -> Optional[str]
"""
Specifies the color theme to distinguish the calendar from other calendars in a UI.
The property values are: auto, lightBlue, lightGreen, lightOrange, lightGray, lightYellow, lightTeal,
lightPink, lightBrown, lightRed, maxColor.
"""
return self.properties.get("color", None)
@property
def default_online_meeting_provider(self):
# type: () -> Optional[str]
"""
The default online meeting provider for meetings sent from this calendar.
Possible values are: unknown, skypeForBusiness, skypeForConsumer, teamsForBusiness.
"""
return self.properties.get("defaultOnlineMeetingProvider", None)
@property
def name(self):
# type: () -> Optional[str]
"""
The calendar name
"""
return self.properties.get("name", None)
@property
def is_default_calendar(self):
# type: () -> Optional[bool]
"""
true if this is the default calendar where new events are created by default, false otherwise.
"""
return self.properties.get("isDefaultCalendar", None)
@property
def is_removable(self):
# type: () -> Optional[bool]
"""
Indicates whether this user calendar can be deleted from the user mailbox.
"""
return self.properties.get("isRemovable", None)
@property
def is_tallying_responses(self):
# type: () -> Optional[bool]
"""
Indicates whether this user calendar supports tracking of meeting responses.
Only meeting invites sent from users' primary calendars support tracking of meeting responses.
"""
return self.properties.get("isTallyingResponses", None)
@property
def owner(self):
"""If set, this represents the user who created or added the calendar.
For a calendar that the user created or added, the owner property is set to the user. For a calendar shared
with the user, the owner property is set to the person who shared that calendar with the user.
"""
return self.properties.get("owner", EmailAddress())
@property
def events(self):
# type: () -> EventCollection
"""The events in the calendar. Navigation property. Read-only."""
return self.properties.get(
"events",
EventCollection(self.context, ResourcePath("events", self.resource_path)),
)
@property
def calendar_view(self):
# type: () -> EventCollection
"""The calendar view for the calendar. Navigation property. Read-only."""
return self.properties.get(
"calendarView",
EventCollection(
self.context, ResourcePath("calendarView", self.resource_path)
),
)
@property
def calendar_permissions(self):
"""The permissions of the users with whom the calendar is shared."""
return self.properties.get(
"calendarPermissions",
CalendarPermissionCollection(
self.context, ResourcePath("calendarPermissions", self.resource_path)
),
)
@property
def multi_value_extended_properties(self):
# type: () -> EntityCollection[MultiValueLegacyExtendedProperty]
"""The collection of multi-value extended properties defined for the Calendar."""
return self.properties.get(
"multiValueExtendedProperties",
EntityCollection(
self.context,
MultiValueLegacyExtendedProperty,
ResourcePath("multiValueExtendedProperties", self.resource_path),
),
)
@property
def single_value_extended_properties(self):
# type: () -> EntityCollection[SingleValueLegacyExtendedProperty]
"""The collection of single-value extended properties defined for the calendar. Read-only. Nullable."""
return self.properties.get(
"singleValueExtendedProperties",
EntityCollection(
self.context,
SingleValueLegacyExtendedProperty,
ResourcePath("singleValueExtendedProperties", self.resource_path),
),
)
def get_property(self, name, default_value=None):
if default_value is None:
property_mapping = {
"allowedOnlineMeetingProviders": self.allowed_online_meeting_providers,
"calendarView": self.calendar_view,
"calendarPermissions": self.calendar_permissions,
"multiValueExtendedProperties": self.multi_value_extended_properties,
"singleValueExtendedProperties": self.single_value_extended_properties,
}
default_value = property_mapping.get(name, None)
return super(Calendar, self).get_property(name, default_value)
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
bases |
Entity | - |
Parameter Details
context: The client context object required for making API calls to Microsoft Graph. Inherited from Entity base class.
resource_path: The resource path identifying this calendar in the Microsoft Graph API hierarchy. Inherited from Entity base class.
Return Value
Instantiation returns a Calendar object that represents a Microsoft 365 calendar. Methods return various types: allowed_calendar_sharing_roles returns ClientResult containing StringCollection of sharing roles; get_schedule returns ClientResult containing ClientValueCollection of ScheduleInformation objects; properties return typed values (bool, str, EmailAddress, EventCollection, etc.) representing calendar metadata and related entities.
Class Interface
Methods
__repr__(self) -> str
Purpose: Returns a string representation of the calendar, preferring name, then id, then entity type name
Returns: String representation of the calendar (name, id, or entity_type_name)
allowed_calendar_sharing_roles(self, user: str) -> ClientResult
Purpose: Retrieves the allowed calendar sharing roles for a specific user
Parameters:
user: User identifier or principal name (email address) to check sharing roles for
Returns: ClientResult containing StringCollection of allowed sharing role names
get_schedule(self, schedules: list[str], start_time: datetime.datetime, end_time: datetime.datetime, availability_view_interval: int = 30) -> ClientResult
Purpose: Gets free/busy availability information for users, distribution lists, or resources for a specified time period
Parameters:
schedules: Collection of SMTP addresses (email addresses) of users, distribution lists, or resources to get availability forstart_time: The date, time, and timezone that the availability period startsend_time: The date, time, and timezone that the availability period endsavailability_view_interval: Duration of time slots in minutes in the availabilityView response (default 30, min 5, max 1440)
Returns: ClientResult containing ClientValueCollection of ScheduleInformation objects with availability data
get_property(self, name: str, default_value=None) -> Any
Purpose: Retrieves a property value by name with optional default value, handling special property mappings
Parameters:
name: The property name to retrievedefault_value: Default value to return if property doesn't exist (optional)
Returns: The property value or default_value if not found
@property allowed_online_meeting_providers(self) -> StringCollection
property
Purpose: Gets the online meeting service providers that can be used to create online meetings in this calendar
Returns: StringCollection of provider names (unknown, skypeForBusiness, skypeForConsumer, teamsForBusiness)
@property can_edit(self) -> Optional[bool]
property
Purpose: Indicates if the user can write to the calendar
Returns: True if user can edit calendar, False otherwise, None if not loaded
@property can_share(self) -> Optional[bool]
property
Purpose: Indicates if the user has permission to share the calendar
Returns: True if user can share calendar, False otherwise, None if not loaded
@property can_view_private_items(self) -> Optional[bool]
property
Purpose: Indicates if the user can read calendar items marked as private
Returns: True if user can view private items, False otherwise, None if not loaded
@property change_key(self) -> Optional[str]
property
Purpose: Gets the version identifier of the calendar object for optimistic concurrency
Returns: String representing the current version of the calendar, None if not loaded
@property color(self) -> Optional[str]
property
Purpose: Gets the color theme to distinguish the calendar in UI
Returns: Color theme name (auto, lightBlue, lightGreen, lightOrange, lightGray, lightYellow, lightTeal, lightPink, lightBrown, lightRed, maxColor), None if not loaded
@property default_online_meeting_provider(self) -> Optional[str]
property
Purpose: Gets the default online meeting provider for meetings sent from this calendar
Returns: Provider name (unknown, skypeForBusiness, skypeForConsumer, teamsForBusiness), None if not loaded
@property name(self) -> Optional[str]
property
Purpose: Gets the calendar name
Returns: Calendar name string, None if not loaded
@property is_default_calendar(self) -> Optional[bool]
property
Purpose: Indicates if this is the default calendar where new events are created
Returns: True if default calendar, False otherwise, None if not loaded
@property is_removable(self) -> Optional[bool]
property
Purpose: Indicates if this calendar can be deleted from the user mailbox
Returns: True if calendar can be removed, False otherwise, None if not loaded
@property is_tallying_responses(self) -> Optional[bool]
property
Purpose: Indicates if this calendar supports tracking of meeting responses
Returns: True if calendar tracks meeting responses, False otherwise, None if not loaded
@property owner(self) -> EmailAddress
property
Purpose: Gets the user who created or added the calendar, or the person who shared it
Returns: EmailAddress object representing the calendar owner
@property events(self) -> EventCollection
property
Purpose: Gets the collection of events in the calendar
Returns: EventCollection navigation property for accessing calendar events
@property calendar_view(self) -> EventCollection
property
Purpose: Gets the calendar view for querying events within a date range
Returns: EventCollection navigation property optimized for date-range queries
@property calendar_permissions(self) -> CalendarPermissionCollection
property
Purpose: Gets the permissions of users with whom the calendar is shared
Returns: CalendarPermissionCollection containing sharing permissions
@property multi_value_extended_properties(self) -> EntityCollection[MultiValueLegacyExtendedProperty]
property
Purpose: Gets the collection of multi-value extended properties defined for the calendar
Returns: EntityCollection of MultiValueLegacyExtendedProperty objects
@property single_value_extended_properties(self) -> EntityCollection[SingleValueLegacyExtendedProperty]
property
Purpose: Gets the collection of single-value extended properties defined for the calendar
Returns: EntityCollection of SingleValueLegacyExtendedProperty objects (read-only, nullable)
Attributes
| Name | Type | Description | Scope |
|---|---|---|---|
context |
ClientContext | The client context for making API requests to Microsoft Graph (inherited from Entity) | instance |
resource_path |
ResourcePath | The resource path identifying this calendar in the API hierarchy (inherited from Entity) | instance |
properties |
dict | Dictionary storing calendar property values loaded from the API (inherited from Entity) | instance |
entity_type_name |
str | The entity type name for this calendar object (inherited from Entity) | instance |
id |
str | The unique identifier for this calendar (inherited from Entity) | instance |
Dependencies
office365typing
Required Imports
from office365.outlook.calendar import Calendar
from office365.entity import Entity
from office365.runtime.client_result import ClientResult
from office365.runtime.types.collections import StringCollection
from office365.outlook.calendar.dateTimeTimeZone import DateTimeTimeZone
from office365.outlook.calendar.schedule.information import ScheduleInformation
from office365.runtime.client_value_collection import ClientValueCollection
Usage Example
from office365.graph_client import GraphClient
from datetime import datetime, timedelta
# Initialize client with credentials
client = GraphClient.with_credentials('client_id', 'client_secret', 'tenant_id')
# Get user's default calendar
calendar = client.me.calendar.get().execute_query()
# Access calendar properties
print(f"Calendar name: {calendar.name}")
print(f"Can edit: {calendar.can_edit}")
print(f"Is default: {calendar.is_default_calendar}")
# Check allowed sharing roles for a user
sharing_roles = calendar.allowed_calendar_sharing_roles('user@example.com')
client.execute_query()
print(f"Sharing roles: {sharing_roles.value}")
# Get schedule availability
start = datetime.now()
end = start + timedelta(days=7)
schedules = ['user1@example.com', 'user2@example.com']
schedule_info = calendar.get_schedule(schedules, start, end, availability_view_interval=30)
client.execute_query()
for info in schedule_info.value:
print(f"Schedule for {info.scheduleId}: {info.availabilityView}")
# Access calendar events
events = calendar.events.get().execute_query()
for event in events:
print(f"Event: {event.subject}")
# Access calendar permissions
permissions = calendar.calendar_permissions.get().execute_query()
for perm in permissions:
print(f"Permission: {perm.role}")
Best Practices
- Always call execute_query() on the context after invoking methods that return ClientResult to actually execute the API request
- Check calendar permissions (can_edit, can_share, can_view_private_items) before attempting write operations
- Use the calendar_view property instead of events when you need to query events within a specific date range for better performance
- When calling get_schedule, ensure datetime objects include timezone information for accurate availability data
- The availability_view_interval parameter in get_schedule must be between 5 and 1440 minutes
- Calendar properties are lazily loaded; access them after calling get() or execute_query() on the parent context
- Use get_property() method to safely access properties with default values to avoid KeyError exceptions
- The owner property represents either the creator or the person who shared the calendar, depending on context
- Extended properties (multi_value_extended_properties and single_value_extended_properties) are read-only collections
- Calendar color values are restricted to predefined theme colors (auto, lightBlue, lightGreen, etc.)
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
class CalendarGroup 78.4% similar
-
class Event 78.2% similar
-
class CalendarPermissionCollection 73.3% similar
-
class CalendarPermission 71.0% similar
-
class ScheduleItem 68.4% similar