为 Google 日历 API 正确格式化 Python 中的日期时间

Formatting datetime in Python properly for Google Calendar API

正在尝试正确格式化日期时间以正确调用 Google 日历 API。以下是我的代码相关部分的代码摘录。

import datetime as DT
now = DT.datetime.today()
seven_days = DT.timedelta(days=7)
oneWeekAgo = now - seven_days

print('Getting the 7 events starting 1 week ago from today: ')
events_result = service.events().list(calendarId='primary', timeMin=oneWeekAgo,
                                      maxResults=7, singleEvents=True).execute()
events = events_result.get('items', [])

基本上我试图从这里修改示例代码: https://developers.google.com/calendar/quickstart/python

示例代码对我来说非常有用,我只想修改它以将要检索的日历事件的日期更改为一周前。我不明白 service.events().list 要求的格式。

感谢您的耐心等待和建议。

客户端库使 API 的使用更容易,但它们只能使用公开可用的方法。也就是说,您应该在官方API文档中对方法Events.list的引用中查找有关参数timeMaxtimeMin的信息:https://developers.google.com/calendar/v3/reference/events/list#parameters

从上面链接的文档中,您有:

timeMax is of type datetime, and described as: Upper bound (exclusive) for an event's start time to filter by. Optional. The default is not to filter by start time. Must be an RFC3339 timestamp with mandatory time zone offset, for example, 2011-06-03T10:00:00-07:00, 2011-06-03T10:00:00Z. Milliseconds may be provided but are ignored. If timeMin is set, timeMax must be greater than timeMin.

我最终在 Google (https://developers.google.com/calendar/quickstart/python) 的示例中使用了相同的解决方案,我只需要弄清楚如何在不更改格式的情况下将日期更改为一周前。

我也加上了今天的最大时间。

  # Call the Calendar API for one week ago through today
now = datetime.today()

oneWeekAgo = now - (DT.timedelta(days=7))

# Let's get this dateTime into the proper format for Google Calendar API

oneWeekAgo = oneWeekAgo.isoformat() + 'Z' # 'Z' indicates UTC time

now = now.isoformat() + 'Z' # 'Z' indicates UTC time

print('Getting up to 20 events starting 1 week ago from today: ')
events_result = service.events().list(calendarId='primary', timeMin=oneWeekAgo,
                                      timeMax=now, maxResults=20, singleEvents=True,
                                      orderBy='startTime').execute()
events = events_result.get('items', [])