This time, I would like to extract arbitrary schedules from the following calendars. I didn't know how to display ** arbitrary schedule **, so I searched quite a bit. After all, looking at the official document, it was one shot ...
So I thought, "Would you like to write everything anyway?", So I wrote it in Qiita.
The basic settings are described in the official document Python Quickstar, so I will skip the details.
Things necessary
--credentials.json file --Calendar ID --Google Client library
You can download the file from here. Put it in the same directory as the main.py
script you are about to create.
The calendar ID can be found in your Google Calendar settings. If you don't know, please google or see here. If you use [My Calendar] → [Name], the calendar ID will be your Gmail address. Other than that (for example, "Test" in the figure below), you can't find out unless you check it.
If you haven't installed the Google Client library, install it.
pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
The sample official documentation is as follows. If you improve this a little, you can do whatever you want.
sample1.py
from __future__ import print_function
import datetime
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/calendar.readonly']
def main():
"""Shows basic usage of the Google Calendar API.
Prints the start and name of the next 10 events on the user's calendar.
"""
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
service = build('calendar', 'v3', credentials=creds)
# Call the Calendar API
now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time
print('Getting the upcoming 10 events')
events_result = service.events().list(calendarId='primary', timeMin=now,
maxResults=10, singleEvents=True,
orderBy='startTime').execute()
events = events_result.get('items', [])
if not events:
print('No upcoming events found.')
for event in events:
start = event['start'].get('dateTime', event['start'].get('date'))
print(start, event['summary'])
if __name__ == '__main__':
main()
The first half of the official document has a lot of code, but the basics are fine. We will transform the code from around # Call the Calendar API
. First, set the list of ʻevents_result` as a sample as follows.
events_result = service.events().list(
calendarId = calendar_id,
q = "test",
timeMin = "2020-02-01T00:00:00+00:00",
timeMax = "2020-02-29T00:00:00+00:00",
timeZone = None,
singleEvents = True,
orderBy = "startTime",
).execute()
events = events_result.get("items", [])
q =" test "
points to the keyword you are searching for. The elements of the list are described in various ways at here, so please try them if you need them.
As a sample, I want to display the schedule for February 2020, so timeMin
and timeMax
specify the range of February with datetime
. You need to be careful here.
Next, we will improve the script after that. You can set this freely, but be careful when reading the description description
of Google Calendar.
if not events:
print("not found")
for event in events:
start = event['start'].get('dateTime',event['start'].get('date'))
description = event.get('description', "not found")
print(start)
print("Event :",event['summary'])
print("Description :",description,"\n")
Use get. ()
as description = event.get ('description'," not found ")
instead of ʻevent ['description']. By the way, if the description is not written in the schedule,
not found` is returned.
Similarly with start = event ['start']. get ('dateTime', event ['start']. get ('date'))
, if the schedule has a time setting, 'dateTime'
Is returned, and if the schedule is all day, ʻevent ['start']. Get ('date')` is returned.
I will connect the above cords. I put the finished coat on it, but I'm making it for myself for other work, so please be patient with the poor use of classes and functions.
main.py
from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/calendar']
calendar_id = "your calendar id"
class Writer(object):
def __init__(self):
"""Shows basic usage of the Google Calendar API.
Prints the start and name of the next 10 events on the user's calendar.
"""
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
self.service = build('calendar', 'v3', credentials=creds)
def google_calendar_reader(self):
events_result = self.service.events().list(
calendarId= calendar_id,
q="test",
timeMin = "2020-02-01T00:00:00+00:00",
timeMax = "2020-02-29T00:00:00+00:00",
timeZone = None,
singleEvents=True,
orderBy="startTime",
).execute()
events = events_result.get("items", [])
if not events:
print("not found")
for event in events:
start = event['start'].get('dateTime',event['start'].get('date'))
description = event.get('description', "not found")
print(start)
print("Event :",event['summary'])
print("Description :",description,"\n")
writer = Writer()
writer.google_calendar_reader()
The output result looks like this.
2020-02-03
Event : test 1
Description : This is description of test_1.
2020-02-10T10:00:00+09:00
Event : test 3
Description : not found
2020-02-11
Event : Test
Description : not found
Well, if you say that you have successfully extracted, you know that it is not. Let's look at the sample calendar again.
Of course, "Test" in the Test calendar is not displayed, but "test_4" is also not displayed. On the contrary, the capital letter "Test" is output. It can be read that the q =
used here is searching for a word with an exact spelling.
Therefore, if you want to display "test", you need to set q =" test "
, and if you want to display "test_4", you need to set q = test_4
.
It seems that it can be used in various ways depending on the application. I feel that I can also analyze behavior such as how often and what I am doing from my schedule.
I'm thinking of using it differently ...
I hope it helps you. Please point out any mistakes. (Please note that " "
and ''
are messed up. I'm sorry.)
--Official documentation for event.list () -Google Calendar API Python Quick Start -How to know the calendar ID of each calendar with Google Calendar
Recommended Posts