【发布时间】:2018-12-13 20:40:51
【问题描述】:
我正在使用 Python Google Calendar APi。
代码:
import datetime
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
# If modifying these scopes, delete the file token.json.
SCOPES = 'https://www.googleapis.com/auth/calendar.readonly'
def main():
"""Shows basic usage of the Google Calendar API.
Prints the start and name of the next 10 events on the user's calendar.
"""
# The file token.json stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
store = file.Storage('token.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('credentials.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'])
if __name__ == '__main__':
main()
如果运行,输出如下所示:
2018-12-26T10:00:00+01:00 Event Name
据我所知,这是 ISO 格式。问题是我找不到将时间格式化为“12 月 26 日,10:00”之类的格式。
我已经尝试了很多东西。
我不能使用.strftime(), .strptime()nordateutil.parser
这是最有希望的: variable = datetime.datetime.strptime(now, '%Y-%m-%d %H:%M:%S.%f').strftime("%B %d, %Y") 但后来我明白了错误..
ValueError: 时间数据 '2018-12-13T11:56:31.095470Z' 与格式 '%Y-%m-%d %H:%M:%S.%f' 不匹配
我在互联网上搜索过,但只找到了一个unanswered question
【问题讨论】:
-
'我不能使用 .strftime()、.strptime()nordateutil.parser',你的意思是你真的不能或者你没有成功使用它们吗?然后你给我们看一个 datetime.strptime 的例子……所以我猜是后者。
-
我没有成功使用它们。错误说“str”没有对象“.strftime”也没有“.strptime”等等
-
你能试试我的答案吗.. 让我知道它是否有效。另外,你能告诉我们
print(start)的结果,看看它返回了什么。
标签: python python-3.x google-api google-calendar-api datetime-format