Home > OS >  Export public Google Calendar events to csv (Python)
Export public Google Calendar events to csv (Python)

Time:10-12

There exists a public Google calendar whose calendar ID I have. I would like to set a start and end date and then get all the events between these dates in a CSV file. What is the most efficient way to do this in Python?

The closest solution I have found is https://stackoverflow.com/a/27213635/1936752 which yields a json file and does not have the filtering by date. I could do this with the json file and writing some code to filter only the dates I want and then export to csv, but I guess there is a smarter way?

The manual way of doing what I want is to download the ics file using the "Export Calendar" function and then using an ics to csv converted like https://openicsfile.com/csv-convert.html. I can then filter easily the dates I want. I wish to do exactly this but using a Python script.

CodePudding user response:

I believe your goal is as follows.

  • You want to retrieve the events from a publicly shared Google Calendar.
  • You want to retrieve the event title and the date as a CSV file.
  • You want to achieve this using python.

In this case, how about the following sample script?

Sample script:

In this sample script, the event list is retrieved using "Events: list" of Calendar API with API key. So, please retrieve your API key. Ref And, please enable Calendar API at the API console.

And, please set the variables of the following sample script.

import csv
from googleapiclient.discovery import build

api_key = "###" # Please set your API key.
calendar_id = "###" # Please set the calendar ID.
start = "2022-10-01T00:00:00Z" # Please set the start date you want to search.
end = "2022-10-31T00:00:00Z" # Please set the end date you want to search.

# Retrieve event list using googleapis for python.
service = build("calendar", "v3", developerKey=api_key)
events_result = service.events().list(calendarId=calendar_id, timeMin=start, timeMax=end, fields="items(summary,start,end)", timeZone="UTC").execute()

# Retrieve the event title and date from all-day events.
allDayEvents = [["Event title", "Date"], *[[e.get("summary"), e.get("start").get("date")] for e in events_result.get("items", []) if e.get("start").get("date") and e.get("end").get("date")]]

# Output the retrieved values as a CSV file.
with open("sample.csv", "w") as f:
    writer = csv.writer(f, lineterminator="\n")
    writer.writerows(allDayEvents)
  • When this script is run, the event list is retrieved from the publicly shared Google Calendar using an API key. And, a CSV file is created by including the event title and the date. In this sample, the all-day events from October 1, 2022 to October 31, 2022 are retrieved.

  • You can see about the googleapis for python at here and here.

References:

  • Related