Integrating Google Calendar API in Python Projects

Pizza
Pizza’s
Published in
3 min readMar 28, 2020

--

Installation

pip install google-api-python-client

OAuth 2.0 Setup

from apiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
scopes = ['https://www.googleapis.com/auth/calendar']flow = InstalledAppFlow.from_client_secrets_file("credentials.json", scopes=scopes)credentials = flow.run_console()Please visit this URL to authorize this application: https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=631411938340-8a3updgnbi6fal2uscjp78ukkrur9htk.apps.googleusercontent.com&redirect_uri=urn%3Aietxxxxxxxxxxxauth%3A2.0%3Aoob&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcalendar&state=MSisnIdm1Yl5VzlmxDCZAXRRSHDMmK&prompt=consent&access_type=offline
Enter the authorization code: 4/xgHDzHKxxxxxxxxxxxxxxsNabdlunl8K3AAnt3YTIKvNHkKcTTHCRE_vsA72k
import picklepickle.dump(credentials, open("token.pkl", "wb"))credentials = pickle.load(open("token.pkl", "rb"))service = build("calendar", "v3", credentials=credentials)

Get My Calendars

result = service.calendarList().list().execute()result['items'][0]{'kind': 'calendar#calendarListEntry',
'etag': '"1583116611031000"',
'id': 'cabie.wu@drshinetech.com',
'summary': 'cabie.wu@xxxxxxxtech.com',
'timeZone': 'Asia/Taipei',
'colorId': '14',
'backgroundColor': '#9fe1e7',
'foregroundColor': '#000000',
'selected': True,
'accessRole': 'owner',
'defaultReminders': [{'method': 'popup', 'minutes': 10}],
'notificationSettings': {'notifications': [{'type': 'eventCreation',
'method': 'email'},
{'type': 'eventChange', 'method': 'email'},
{'type': 'eventCancellation', 'method': 'email'},
{'type': 'eventResponse', 'method': 'email'}]},
'primary': True,
'conferenceProperties': {'allowedConferenceSolutionTypes': ['hangoutsMeet']}}

Get My Calendar Events

calendar_id = result['items'][0]['id']result = service.events().list(calendarId=calendar_id, timeZone="Asia/Taipei").execute()result['items'][0]{'kind': 'calendar#event',
'etag': '"3167993763372000"',
'id': '0ifjcc5cd656iumvvj9q49nd92',
'status': 'confirmed',
'htmlLink': 'https://www.google.com/calendar/event?eid=MGlmamNjNWNkNjU2aXVtdnZqOXE0OW5kOTIgY2FiaWUud3VAZHJzaGluZXRlY2guY29t&ctz=Asia/Taipei',
'created': '2020-03-12T07:04:32.000Z',
'updated': '2020-03-12T07:08:01.758Z',
'summary': 'cal_test',
'creator': {'email': 'cabie.wu@xetechxxxx.com', 'self': True},
'organizer': {'email': 'cabie.wu@xxxxxxtech.com', 'self': True},
'start': {'dateTime': '2020-03-12T12:00:00+08:00'},
'end': {'dateTime': '2020-03-12T13:00:00+08:00'},
'transparency': 'transparent',
'iCalUID': '0ifjcc5cd656iumvvj9q49nd92@google.com',
'sequence': 1,
'reminders': {'useDefault': False,
'overrides': [{'method': 'popup', 'minutes': 10}]}}
from pprint import pprintpprint(result['items'])[{'created': '2020-03-12T07:04:32.000Z',
'creator': {'email': 'cabie.wu@xxxxtech.com', 'self': True},
'end': {'dateTime': '2020-03-12T13:00:00+08:00'},
'etag': '"3167993763372000"',
'htmlLink': 'https://www.google.com/calendar/event?eid=MGlmamNjNWNkNjU2aXVtdnZqOXE0OW5kOTIgY2FiaWUud3VAZHJzaGluZXRlY2guY29t&ctz=Asia/Taipei',
'iCalUID': '0ifjcc5cd656iumvvj9q49nd92@google.com',
'id': '0ifjcc5cd656iumvvj9q49nd92',
'kind': 'calendar#event',
'organizer': {'email': 'cabie.wu@xxxxtech.com', 'self': True},
'reminders': {'overrides': [{'method': 'popup', 'minutes': 10}],
'useDefault': False},
'sequence': 1,
'start': {'dateTime': '2020-03-12T12:00:00+08:00'},
'status': 'confirmed',
'summary': 'cal_test',
'transparency': 'transparent',
'updated': '2020-03-12T07:08:01.758Z'},
{'created': '2020-03-12T07:09:37.000Z',
'creator': {'email': 'cabie.wu@xxxxtech.com', 'self': True},
'description': 'MI vs TBD',
'end': {'dateTime': '2020-03-15T23:30:00+08:00', 'timeZone': 'Asia/Taipei'},
'etag': '"3167993956040000"',
'htmlLink': 'https://www.google.com/calendar/event?eid=ZzF2b3NrNG0yMjk1djhwamlpYmphaWFqY2sgY2FiaWUud3VAZHJzaGluZXRlY2guY29t&ctz=Asia/Taipei',
'iCalUID': 'g1vosk4m2295v8pjiibjaiajck@google.com',
'id': 'g1vosk4m2295v8pjiibjaiajck',
'kind': 'calendar#event',
'location': 'Hyderabad',
'organizer': {'email': 'cabie.wu@xxxxtech.com', 'self': True},
'reminders': {'overrides': [{'method': 'email', 'minutes': 1440},
{'method': 'popup', 'minutes': 10}],
'useDefault': False},
'sequence': 0,
'start': {'dateTime': '2020-03-15T19:30:00+08:00', 'timeZone': 'Asia/Taipei'},
'status': 'confirmed',
'summary': 'IPL Final 2019',
'updated': '2020-03-12T07:09:38.077Z'}]

Create a New Calandar Event

from datetime import datetime, timedeltastart_time = datetime(2020, 3, 15, 19, 30, 0)
end_time = start_time + timedelta(hours=4)
timezone = 'Asia/Taipei'
event = {
'summary': 'IPL Final 2019',
'location': 'Hyderabad',
'description': 'MI vs TBD',
'start': {
'dateTime': start_time.strftime("%Y-%m-%dT%H:%M:%S"),
'timeZone': timezone,
},
'end': {
'dateTime': end_time.strftime("%Y-%m-%dT%H:%M:%S"),
'timeZone': timezone,
},
'reminders': {
'useDefault': False,
'overrides': [
{'method': 'email', 'minutes': 24 * 60},
{'method': 'popup', 'minutes': 10},
],
},
}
service.events().insert(calendarId=calendar_id, body=event).execute(){'kind': 'calendar#event',
'etag': '"3167993956040000"',
'id': 'g1vosk4m2295v8pjiibjaiajck',
'status': 'confirmed',
'htmlLink': 'https://www.google.com/calendar/event?eid=ZzF2b3NrNG0yMjk1djhwamlpYmphaWFqY2sgY2FiaWUud3VAZHJzaGluZXRlY2guY29t',
'created': '2020-03-12T07:09:37.000Z',
'updated': '2020-03-12T07:09:38.077Z',
'summary': 'IPL Final 2019',
'description': 'MI vs TBD',
'location': 'Hyderabad',
'creator': {'email': 'cabie.wu@xxxxtech.com', 'self': True},
'organizer': {'email': 'cabie.wu@xxxxtech.com', 'self': True},
'start': {'dateTime': '2020-03-15T19:30:00+08:00', 'timeZone': 'Asia/Taipei'},
'end': {'dateTime': '2020-03-15T23:30:00+08:00', 'timeZone': 'Asia/Taipei'},
'iCalUID': 'g1vosk4m2295v8pjiibjaiajck@google.com',
'sequence': 0,
'reminders': {'useDefault': False,
'overrides': [{'method': 'popup', 'minutes': 10},
{'method': 'email', 'minutes': 1440}]}}

Utility function

pip install datefinder! pip install datefinderCollecting datefinder
Downloading datefinder-0.7.0-py2.py3-none-any.whl (8.8 kB)
Requirement already satisfied: python-dateutil>=2.4.2 in /home/cabie/anaconda3/lib/python3.7/site-packages (from datefinder) (2.8.1)
Requirement already satisfied: pytz in /home/cabie/anaconda3/lib/python3.7/site-packages (from datefinder) (2019.3)
Collecting regex>=2017.02.08
Downloading regex-2020.2.20-cp37-cp37m-manylinux2010_x86_64.whl (689 kB)
�[K |████████████████████████████████| 689 kB 1.7 MB/s eta 0:00:01
�[?25hRequirement already satisfied: six>=1.5 in /home/cabie/anaconda3/lib/python3.7/site-packages (from python-dateutil>=2.4.2->datefinder) (1.14.0)
Installing collected packages: regex, datefinder
Successfully installed datefinder-0.7.0 regex-2020.2.20
import datefindermatches = datefinder.find_dates("15 march 9 PM")list(matches)[datetime.datetime(2020, 3, 15, 21, 0)]def create_event(start_time_str, summary, duration=1, description=None, location=None):
matches = list(datefinder.find_dates(start_time_str))
if len(matches):
start_time = matches[0]
end_time = start_time + timedelta(hours=duration)

event = {
'summary': summary,
'location': location,
'description': description,
'start': {
'dateTime': start_time.strftime("%Y-%m-%dT%H:%M:%S"),
'timeZone': 'Asia/Kolkata',
},
'end': {
'dateTime': end_time.strftime("%Y-%m-%dT%H:%M:%S"),
'timeZone': 'Asia/Kolkata',
},
'reminders': {
'useDefault': False,
'overrides': [
{'method': 'email', 'minutes': 24 * 60},
{'method': 'popup', 'minutes': 10},
],
},
}
return service.events().insert(calendarId='primary', body=event).execute()
create_event("15 may 9 PM", "Meeting"){'kind': 'calendar#event',
'etag': '"3167994743918000"',
'id': 'ivf8uucqsc48vpb3at4gvf4ekk',
'status': 'confirmed',
'htmlLink': 'https://www.google.com/calendar/event?eid=aXZmOHV1Y3FzYzQ4dnBiM2F0NGd2ZjRla2sgY2FiaWUud3VAZHJzaGluZXRlY2guY29t',
'created': '2020-03-12T07:16:11.000Z',
'updated': '2020-03-12T07:16:12.005Z',
'summary': 'Meeting',
'creator': {'email': 'cabie.wu@xxxxtech.com', 'self': True},
'organizer': {'email': 'cabie.wu@xxxxtech.com', 'self': True},
'start': {'dateTime': '2020-05-15T23:30:00+08:00',
'timeZone': 'Asia/Kolkata'},
'end': {'dateTime': '2020-05-16T00:30:00+08:00', 'timeZone': 'Asia/Kolkata'},
'iCalUID': 'ivf8uucqsc48vpb3at4gvf4ekk@google.com',
'sequence': 0,
'reminders': {'useDefault': False,
'overrides': [{'method': 'popup', 'minutes': 10},
{'method': 'email', 'minutes': 1440}]}}

--

--