hayateasdf's blog

Unity,C#, javascript,C++,python,batなど

Google Calendarから祝日を取得

環境

  • VS Code

  • Python 3.6.2

    • pip install

OAuth認証でGoogle Calendar APIに接続する(python 編)

quickstart.pyを実行し、カレンダー利用の許可。
このコードはholiday.pyにリネームする。

GoogleカレンダーAPIを使って、日本の祝日を取得する

コードの下記のAPI実行の部分を利用する。
holiday.pyに記述。

Pythonで「指定した年と月」の「すべての日付」を表示する関数をつくってみた

上記の方法で1年分のカレンダーを作成する。
新規でtest.py作成

holiday.py

from __future__ import print_function
import httplib2
import os

from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage

from datetime import date

try:
    import argparse
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags = None

# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/calendar-python-quickstart.json
SCOPES = 'https://www.googleapis.com/auth/calendar.readonly'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Google Calendar API Python Quickstart'


def _get_credentials():
    """Gets valid user credentials from storage.

    If nothing has been stored, or if the stored credentials are invalid,
    the OAuth2 flow is completed to obtain the new credentials.

    Returns:
        Credentials, the obtained credential.
    """
    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir,
                                   'calendar-python-quickstart.json')

    store = Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        if flags:
            credentials = tools.run_flow(flow, store, flags)
        else: # Needed only for compatibility with Python 2.6
            credentials = tools.run(flow, store)
        print('Storing credentials to ' + credential_path)
    return credentials

def get_holiday_events(year):
    """Shows basic usage of the Google Calendar API.

    Creates a Google Calendar API service object and outputs a list of the next
    10 events on the user's calendar.
    """
    credentials = _get_credentials()
    http = credentials.authorize(httplib2.Http())
    service = discovery.build('calendar', 'v3', http=http)

    calendar_id = 'ja.japanese#holiday@group.v.calendar.google.com'
    calendar_min = date(year=year, month=1, day=1).isoformat() + 'T00:00:00.000000Z'
    calendar_max = date(year=year, month=12, day=31).isoformat() + 'T00:00:00.000000Z'

    event_results = service.events().list(
      calendarId = calendar_id,
      timeMin = calendar_min,
      timeMax = calendar_max,
      maxResults = 50,
      singleEvents = True,
      orderBy = "startTime"
    ).execute()

    events = event_results.get('items', [])
    # for event in events:
    #   print("%s\t%s" % (event["start"]["date"], event["summary"]))
    
    return events;

test.py

import calendar
import holiday
from datetime import date

def get_year_days(year, month):
  month_days = [i+1 for i in range(calendar.monthrange(year, month)[1])]
  days = list(map(lambda day: "{0:02d}/{1:02d}/{2:02d}".format(year, month, day), month_days))
  return days

def main(year):
  months = [i+1 for i in range(12)]
  year_days = list(map(lambda month: get_year_days(year, month), months))

  events = holiday.get_holiday_events(year)
  holiday_dict = dict(
        (event["start"]["date"].replace("-", "/"), event["summary"])
        for event in events
      )

  for month in year_days:
    for day in month:
      if day in holiday_dict:
        print(day + " " + holiday_dict[day])
      else:
        print(day)

if __name__ == '__main__':
  main(2017)

結果

2017/01/01 元日
2017/01/02 元日 振替休日
2017/01/03
2017/01/04
2017/01/05
2017/01/06
2017/01/07
2017/01/08
2017/01/09 成人の日
2017/01/10
2017/01/11
2017/01/12
...
2017/12/23 天皇誕生日
2017/12/24
2017/12/25
2017/12/26
2017/12/27
2017/12/28
2017/12/29
2017/12/30
2017/12/31