Google calendar automation using python

Google Calendar is a time-management and scheduling calendar service developed by Google. It’s a popular tool used by individuals and businesses to manage their daily schedules and events. With the Google Calendar API, you can automate various tasks, such as adding events, retrieving events, and managing calendars. In this blog, we will discuss how to automate Google Calendar using Python.

In my previous blog I shared how to automation google sheets using python.

Setting up a Google Developer Account

The first step is to create a Google Developer account, which will allow you to access Google’s APIs, including the Google Calendar API. You can create a Google Developer account by visiting the Google Developers Console. Create a new project if you do not have one already.

Enabling the Google Calendar API

After creating a project, the next step is to enable the Google Calendar API. You can do this by navigating to the Google Developers Console, selecting “API Library,” and then selecting “Google Calendar API.”

Installing the Google API Client Library for Python

In order to interact with the Google Calendar API, you will need to install the Google API Client Library for Python. This library provides access to the Google Calendar API and enables you to write code that interacts with the API.

pip install oauth2client

Authenticating with the Google Calendar API

After installing the Google API Client Library for Python, you will need to authenticate with the API in order to access your Google Calendar data. This requires creating a credentials object and passing it to the API client.

  • Go to “IAM & Admin” and select “Service accounts” and click “create service account” at top. 
  • Enter a service account name and click done.
  • Under action click Manage keys as shown below.
  • Click “ADD KEY” dropdown and select “Create new key”.
  • Select json and click create. Store the download JSON in your system.

Adding an Event to Google Calendar

With the API set up and authenticated, you can now start automating tasks with Python. The first task we’ll cover is adding an event to your Google Calendar. To do this, you will need to create an event object and then call the events().insert() method, passing in the calendar ID and event object.

Adding permission to access Google calendar

Open the credential JSON file that you download and copy the “client_email”. Open the google calendar which you like to automate and add permission to this email ID with “Make changes to events” permission.

Retrieving Events from Google Calendar

Another useful task you can automate with the Google Calendar API is retrieving events from your calendar. To do this, you can call the events().list() method, passing in the calendar ID and any other parameters you want to use to filter the events.

Managing Calendars with the Google Calendar API

The Google Calendar API also provides the ability to manage calendars, including creating new calendars, updating existing calendars, and deleting calendars. You can perform these actions using the calendars().insert(), calendars().patch(), and calendars().delete() methods, respectively.

Sample Code

Create a python file in the same directory where you have the credential JSON downloaded. You can rename the JSON file into creds.json

from oauth2client.service_account import ServiceAccountCredentials
from googleapiclient.discovery import build
from datetime import datetime,timedelta

scope = ["https://www.googleapis.com/auth/calendar"]

creds = ServiceAccountCredentials.from_json_keyfile_name("creds.json",scope)
API_NAME = 'calendar'
API_VERSION = 'v3'

# google calendar service
service = build(API_NAME, API_VERSION, credentials=creds)

calendar_id = "YOUR_CALENDAR_ID"

time_min = datetime.now()
time_max = time_min + timedelta(hours=20)


# freebusy
payload = {
    "timeMin": time_min.strftime("%Y-%m-%dT%H:%M:%S+05:30"),
    "timeMax": time_max.strftime("%Y-%m-%dT%H:%M:%S+05:30"),
    # "timeZone": timezone,
    "items": [{ "id": calendar_id }],
}
print(payload)

freebusy = service.freebusy().query(body=payload).execute()

print(freebusy)

#insert
time_min = datetime.now()
time_max = time_min + timedelta(hours=1)
event = {
    'summary': 'test summary',
    'description': "description test",
    'start': {
        'dateTime': time_min.strftime("%Y-%m-%dT%H:%M:%S+05:30"),
        # 'timeZone': timezone,
    },
    'end': {
        'dateTime': time_max.strftime("%Y-%m-%dT%H:%M:%S+05:30"),
        # 'timeZone': timezone,
    },
    'reminders': {
        'useDefault': False,
        'overrides': [
        {'method': 'popup', 'minutes': 30},
        ],
    },
}
print(service.events().insert(calendarId=calendar_id, body=event).execute())

#delete
# events = service.events().list(calendarId=calendar_id,timeMin=time_min.strftime("%Y-%m-%dT%H:%M:%S+05:30"),timeMax=time_max.strftime("%Y-%m-%dT%H:%M:%S+05:30")).execute()
# print(events)
# for reservation in events["items"]:
#     print(service.events().delete(calendarId=calendar_id,eventId = reservation["id"]).execute())
    

In conclusion, automating Google Calendar with Python is a powerful tool that can save you time and effort by allowing you to automate various tasks, such as adding events, retrieving events, and managing calendars. With the Google Calendar API, you can easily integrate Google Calendar into your own applications and automate various tasks to make your life easier.

Leave a Comment