Skip to main content
 首页 » 编程设计

python之从特定日历 Google API Python 获取事件

2024年12月31日10jiqing9006

我使用 Google API 中的 quickstart.py 代码从日历中获取事件。它是下面的代码,确切的步骤在这里 https://developers.google.com/calendar/quickstart/python

from __future__ import print_function 
from apiclient.discovery import build 
from httplib2 import Http 
from oauth2client import file, client, tools 
import datetime 
 
# Setup the Calendar API 
SCOPES = 'https://www.googleapis.com/auth/calendar.readonly' 
store = file.Storage('credentials.json') 
creds = store.get() 
if not creds or creds.invalid: 
    flow = client.flow_from_clientsecrets('client_secret.json', SCOPES) 
    creds = tools.run_flow(flow, store) 
service = build('calendar', 'v3', http=creds.authorize(Http())) 
 
# 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']) 

这对我来说很好用。现在我在我的帐户中添加了另一个日历,将我的代码复制到另一个文件夹并再次运行这些步骤(谷歌链接)。我把secound.json放到了secound文件夹下测试了一下。

即使它应该能够访问两个日历,它也只能从第一个日历中检索事件。所以我想知道如何访问另一个日历(最好只有第二个日历,但我同时使用它们也会有帮助)。

我确实搜索了没有帮助的 Google 文档,我发现的每个 Stackoverflow 问题都依赖于另一种编程语言(而且我未能将其附加到 python)或者答案包含指向不再存在的网站的链接。

非常感谢!

请您参考如下方法:

您需要选择要从中检索事件的日历,并将正确的 calendarId 传递给 service.events().list() . 'primary' 总是可以用来获取用户的主日历,可以用service.calendarList().list() 获取用户拥有的所有日历信息。 .