Create ICS Calendar File in Python

An ICS file is an iCalendar file having .ics extension. An ICS file contains plain text with calendar event details such as starting and ending time of events, event description, etc.

In this example, we will use icalendar to create an ICS file in Python. icalendar is a Python library used to parse and generate iCalendar files.

Install icalendar

pip3 install icalendar

Here's a snippet of Python code to createn .ics file:


from icalendar import Calendar, Event
import pytz
from datetime import datetime
import os
from pathlib import Path

cal = Calendar()
cal.add('attendee', 'MAILTO:abc@example.com')
cal.add('attendee', 'MAILTO:xyz@example.com')

event = Event()
event.add('summary', 'Python meeting about calendaring')
event.add('dtstart', datetime(2021, 4, 4, 8, 0, 0, tzinfo=pytz.utc))
event.add('dtend', datetime(2021, 4, 4, 10, 0, 0, tzinfo=pytz.utc))
event.add('dtstamp', datetime(2021, 4, 4, 0, 10, 0, tzinfo=pytz.utc))

# Adding events to calendar
cal.add_component(event)

directory = str(Path(__file__).parent.parent) + "/"
print(directory)
f = open(os.path.join(directory, 'example.ics'), 'wb')
f.write(cal.to_ical())
f.close()

Read more in detail here.