检索用户在该时间点的 google 日历

Retrieving a user's google calendar at the point in time

我正在尝试检索用户当前的 google 日历事件(即在某个时间点)。如您所见,我必须创建一个嵌套循环来遍历用户的 every google 日历。然而,我并不总能得到正确的事件。我不确定我的错误是什么,也不知道是否有 better/conciser 这样做的方法。

    utc_dt = datetime.now(timezone.utc).astimezone().isoformat()
    service = build('calendar', 'v3', credentials=credentials)
    events_result =service.calendarList().list().execute()
    events = events_result.get('items', [])
    Ids = [item['id'] for item in events] #getting more colors because events is not taking the time AlCals is taking
    import pytz
    utc=pytz.UTC
    AllCals = [service.events().list(calendarId=id, timeMin=utc_dt, maxResults=1, singleEvents=True).execute() for id in Ids ]
    calEvent = []
    now = datetime.now()
    for calendar in AllCals:
        for item in calendar["items"]:
            if "dateTime" in item["start"] and item["end"]:
                if datetime.strptime(item["start"]["dateTime"], "%Y-%m-%dT%H:%M:%S%z"):
                    calEvent.append(item)
    now = datetime.now(pytz.utc)
    name = max(dt['summary'] for dt in calEvent if datetime.strptime(dt["start"]["dateTime"], "%Y-%m-%dT%H:%M:%S%z") < now)
    return {'current event':name}

线路有问题

service.events().list(calendarId=id, timeMin=utc_dt, maxResults=1, singleEvents=True).execute()

maxResults=1 表示您访问的每个日历最多列出 1 个事件!

如果您想检索 1 个以上的事件 - 跳过此参数。

你必须提到获得事件结果的顺序,否则它会重新运行随机事件。添加参数 orderBy='startTime',如果您想从开始日期获取事件数,则在 maxResults 中传递该数字,否则删除 maxResults 参数。

events_result = service.events().list(calendarId=id, timeMin=utc_dt,
                                              maxResults=10, singleEvents=True,
                                              orderBy='startTime').execute()