How to extract any appointment in Google Calendar with Python

Introduction

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.

image.png

Introduction

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. image.png

If you haven't installed the Google Client library, install it.

pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib

Official sample

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()

Search for any appointment

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.

Arrange the display

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.

Implementation

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.

image.png

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.

Summary

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.)

References

--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

How to extract any appointment in Google Calendar with Python
How to work with BigQuery in Python
How to extract polygon area in Python
[REAPER] How to play with Reascript in Python
How to use tkinter with python in pyenv
How to develop in Python
How to convert / restore a string with [] in python
How to do hash calculation with salt in Python
Explain in detail how to make sounds with python
How to run tests in bulk with Python unittest
How to load files in Google Drive with Google Colaboratory
How to drop Google Docs in one folder in a .txt file with python
[Python] How to do PCA in Python
Python: How to use async with
How to collect images in Python
How to use SQLite in Python
How to get started with Python
How to sample from any probability density function in Python
How to use Mysql in python
How to wrap C in Python
How to use ChemSpider in Python
How to use FTP with Python
How to use PubChem in Python
How to calculate date with python
How to handle Japanese in Python
How to log in to AtCoder with Python and submit automatically
How to deal with python installation error in pyenv (BUILD FAILED)
How to not escape Japanese when dealing with json in python
How to create a heatmap with an arbitrary domain in Python
How to use python put in pyenv on macOS with PyCall
How to connect to Cloud Firestore from Google Cloud Functions with python code
How to display legend marks in one with Python 2D plot
How to calculate "xx time" in one shot with Python timedelta
[Introduction to Python] How to use class in Python?
Try logging in to qiita with Python
How to access environment variables in Python
How to dynamically define variables in Python
How to do R chartr () in Python
How to update Google Sheets from Python
[Itertools.permutations] How to put permutations in Python
How to use Google Test in C
How to get a stacktrace in python
How to display multiplication table in python
How to do portmanteau test with python
How to search Google Drive with Google Colaboratory
How to check opencv version in python
How to display python Japanese with lolipop
How to switch python versions in cloud9
How to adjust image contrast in Python
How to use __slots__ in Python class
How to dynamically zero pad in Python
How to enter Japanese with Python curses
To work with timestamp stations in Python
How to use regular expressions in Python
[Python] How to deal with module errors
How to display Hello world in python
How to use is and == in Python
How to write Ruby to_s in Python
Upload images to Google Drive with Python
How to install python3 with docker centos
How to deal with OAuth2 error when using Google APIs from Python