Last active
January 14, 2024 14:25
-
-
Save kujirahand/f7fd942cee5f8313afe784f9d579ba2b to your computer and use it in GitHub Desktop.
Google Calendar APIを使ってカウントダウン
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import datetime | |
from googleapiclient.discovery import build | |
from google.auth import load_credentials_from_file | |
# クレデンシャルファイルのパスを指定 --- (*1) | |
CREDENTIALS_PATH = 'credentials.json' | |
# カレンダーIDを指定 --- (*2) | |
CALENDAR_ID = '28e4bb3f327eb238d29a282e9935fc957c40bb3e63ae831b9ecc935bee67efed@group.calendar.google.com' | |
# スコープの指定 | |
SCOPES = ['https://www.googleapis.com/auth/calendar.readonly'] | |
# クレデンシャル情報の読み込み --- (*3) | |
credentials = load_credentials_from_file(CREDENTIALS_PATH, SCOPES)[0] | |
# Google Calendar APIクライアントの作成 --- (*4) | |
service = build('calendar', 'v3', credentials=credentials) | |
# イベントの開始日を指定 --- (*5) | |
now = datetime.datetime.utcnow() | |
start_date = now.isoformat() + 'Z' | |
# イベントの終了日を指定(ここでは30日後まで) --- (*6) | |
end_date = (now + datetime.timedelta(days=30)).isoformat() + 'Z' | |
# イベントの一覧を取得 --- (*7) | |
events_result = service.events().list( | |
calendarId=CALENDAR_ID, | |
timeMin=start_date, | |
timeMax=end_date, | |
singleEvents=True, | |
maxResults=30, # 最大30件のイベントを取得 | |
orderBy='startTime' | |
).execute() | |
events = events_result.get('items', []) | |
# イベントを表示 --- (*8) | |
if not events: | |
print('イベントは見つかりませんでした。') | |
else: | |
print('イベント一覧:') | |
for event in events: | |
# イベントの開始時間を取得 | |
target_date = event['start'].get('dateTime', event['start'].get('date')) | |
# そのイベントまで何日あるか調べて表示 --- (*9) | |
if 'T' in target_date: # タイムスタンプがあれば除去 | |
target_date = target_date[:10] | |
now = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0) | |
target_td = datetime.datetime.strptime(target_date, '%Y-%m-%d') | |
days = (target_td - now).days | |
print(f'{days:2}日 - {event["summary"]}') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment