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 for parsing and generating iCalendar files.

Follow these steps to create an .ics file using the icalendar library in Python:

  1. Install icalendar:
  2. pip install icalendar
  3. Example:
  4. Here's a code snippet to create an .ics file in Python:

    from icalendar import Calendar, Event, vCalAddress, vText
    import pytz
    from datetime import datetime
    import os
    from pathlib import Path
    cal = Calendar()
    cal.add('attendee', '')
    cal.add('attendee', '')
    event = Event()
    event.add('summary', 'Python meeting about calendaring')
    event.add('dtstart', datetime(2022, 10, 24, 8, 0, 0, tzinfo=pytz.utc))
    event.add('dtend', datetime(2022, 10, 24, 10, 0, 0, tzinfo=pytz.utc))
    event.add('dtstamp', datetime(2022, 10, 24, 0, 10, 0, tzinfo=pytz.utc))
    organizer = vCalAddress('')
    organizer.params['cn'] = vText('Sir Jon')
    organizer.params['role'] = vText('CEO')
    event['organizer'] = organizer
    event['location'] = vText('London, UK')
    # Adding events to calendar
    directory = str(Path(__file__).parent.parent) + "/"
    print("ics file will be generated at ", directory)
    f = open(os.path.join(directory, 'example.ics'), 'wb')