Skip to main content
 首页 » 编程设计

python之Google Calendar API 日期时间格式 python

2025年01月19日10zhujiabin

我正在尝试使用适用于 python 的 Google Calendar API,并希望更改它输出的日期格式。我试过使用 dateutil 和 strftime,但无法正常工作......

现在它正在输出 yyyy-mm-dd hh:mm:ss-hh:mm “事件名称”。

我希望它只显示 yyyy-mm-dd 或类似“2018 年 4 月 15 日”的格式。

非常感谢您!

""" 
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() 

请您参考如下方法:

您可能已经找到了这个问题的解决方案,但是 another question让我想到了这个“未回答”的问题。

同样的答案..

您可以将 dateutil.parser 和 datetime.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)