谷歌日历API日期时间格式Python

3

我正在尝试使用Python的Google日历API,并希望更改其输出的日期格式。我已经尝试使用dateutil和strftime,但无法使其正常工作...

目前它输出的格式为yyyy-mm-dd hh:mm:ss-hh:mm "事件名称"。

我希望它只显示yyyy-mm-dd,或者以“Apr 15, 2018”这样的格式显示。

谢谢你,感激不尽!

"""
Shows basic usage of the Google Calendar API. Creates a Google Calendar API
service object and outputs a list of the next 10 events on the user's calendar.
"""
from __future__ import print_function
from apiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
import datetime
import time

# 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', [])

outFile = open('sample.txt' , 'w')

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'])

    outFile.write(str(event['summary']))
    outFile.write('  ')
    outFile.write(start)
    outFile.write('\n')
outFile.close()

可能是重复的问题,与https://dev59.com/o3NA5IYBdhLWcg3wa9Kp相似。 - ReyAnthonyRenacia
3个回答

1
如果你想将Python的datetime转换为Google API格式,可以使用以下日期时间格式:
datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%fZ')

1
你可能已经找到了这个问题的解决方案,但另一个问题引导我来到这个“未回答”的问题。
相同的答案。。 您可以使用dateutil.parserdatetime.datetime.strftime一起完成它。
from dateutil.parser import parse as dtparse
from datetime import datetime as dt

start = '2018-12-26T10:00:00+01:00'   # Let's say your start value returns this as 'str'
tmfmt = '%d %B, %H:%M %p'             # Gives you date-time in the format '26 December, 10:00 AM' as you mentioned

# now use the dtparse to read your event start time and dt.strftime to format it
stime = dt.strftime(dtparse(start), format=tmfmt)

输出:

Out[23]: '26 December, 10:00 AM'

然后使用下面的命令打印事件或将4个outfile.write命令合并为一个,按以下方式写入文件:

print(stime, event['summary'])
outFile.write("{}\t{}\n".format(str(event['summary']), stime)

0

我假设start变量包含您想要打印的datetime对象。如果是这样,您可以通过调用strftime(思考:从时间中获取字符串)来格式化它。从日期时间对象返回一个字符串:

date_format = '%Y-%m-%d'
print(start.strftime(date_format), event['summary'])

文档(链接)包含一个表格,解释了各种格式选项。


我收到了以下错误信息: AttributeError: 'unicode' object has no attribute 'strftime'我需要安装strftime吗? - Jae Park
也许strftime不起作用是因为我的代码输出的是时间范围,而不仅仅是一个特定的日期和时间。 - Jae Park

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接