2014年12月13日

PythonでGoogle Calendar APIから日本の祝祭日を取得する

日本の祝祭日の情報が欲しかったんだけど、あまり良いAPIが見当たらなかったので、Google CalendarのAPIから取得することにする。こういう情報は国がcsvでもなんでも良いからさらっと提供してくれると助かるのだけど。

google-api-python-clientを利用する。認証とかあるので自前で実装するのは手間だし、GoogleのAPIは仕様変更もけっこうあるので、ライブラリ噛ませておくのが正着だと思う。

google-api-python-client
https://github.com/google/google-api-python-client

インストール

pip install --upgrade google-api-python-client

下記のように実行するらしい

from apiclient.discovery import build
service = build(serviceName='calendar', version='v3', developerKey='<your_api_key>')
events = service.events().list(calendarId='<calendar_id>').execute()

コードは下記を参考にした
http://stackoverflow.com/questions/14058964/using-google-calendar-api-v-3-with-python

祝祭日のcalendar_idは下記らしい

ja.japanese#holiday@group.v.calendar.google.com

api_keyについては下記あたりから拾ってくる(Googleのアカウントは持っていること)
https://console.developers.google.com/project

下記の手順をこなす。

  • APIs & auth → APIsからCalendar APIが有効になってることを確認
  • APIs & auth → Credentialsから、Create new KeyしてとりあえずBrowser Keyで作る → 出来上がったKeyをメモする

情報が揃ったので実行してみる

API_KEY = '上の手順で拾ったkey'
CALENDAR_ID = 'ja.japanese#holiday@group.v.calendar.google.com'

# APIを叩く
from apiclient.discovery import build
service = build(serviceName='calendar', version='v3', developerKey=API_KEY)
events = service.events().list(calendarId=CALENDAR_ID).execute()

# 取得結果表示
for item in events['items']:
  print( u'{0}\t{1}'.format( item['start']['date'], item['summary'] ) )

# 見づらいのでソート
for item in sorted(events['items'], key=lambda item: item['start']['date']):
  print( u'{0}\t{1}'.format( item['start']['date'], item['summary'] ) )

これで良い感じに取れた。