[英]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
的參考中查找有關參數timeMax
和timeMin
的信息: https://developers.google.com/calendar/v3/reference/events /列表#參數
從上面鏈接的文檔中,您有:
timeMax
是 datetime 類型,描述為:過濾事件開始時間的上限(不包括)。 可選的。 默認不按開始時間過濾。 必須是帶有強制時區偏移的 RFC3339 時間戳,例如,2011-06-03T10:00:00-07:00、2011-06-03T10:00:00Z。 可以提供毫秒但被忽略。 如果設置了 timeMin,則 timeMax 必須大於 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', [])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.