问题描述
我正在尝试使用适用于python的Google Calendar API,并希望更改其输出日期的格式.我尝试使用dateutil和strftime,但无法使其正常工作.....
I'm trying to use the Google Calendar API for python and want to change the format of the date it's outputting. I've tried using dateutil and strftime, but couldn't get it to work.....
现在它正在输出yyyy-mm-dd hh:mm:ss-hh:mm事件名称".
Right now it's outputting yyyy-mm-dd hh:mm:ss-hh:mm "Event Name".
我希望它只显示yyyy-mm-dd或"2018年4月15日"之类的格式.
I want it to just display either yyyy-mm-dd, or in a format like "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()
推荐答案
您可能已经找到了解决此问题的方法,但将我带到了这个"未回答"问题.
You probably have found a solution to this question but another question brought me to this 'Unanswered' question.
相同的答案..
您可以将dateutil.parser
和datetime.datetime.strftime
一起使用.
You can do it using dateutil.parser
and datetime.datetime.strftime
together.
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)
这篇关于Google Calendar API日期时间格式python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!