格式化Google日历活动日期

格式化Google日历活动日期

本文介绍了格式化Google日历活动日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Python Google Calendar APi。

Im working with the 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()

如果运行,输出如下所示:

If run, the output looks like this:

2018-12-26T10:00:00+01:00 Event Name

从我所知这就是ISO格式。问题是我找不到将时间格式化为类似于 12月26日10:00这样的人类的方法。

That is ISO format from what I know. The problem is that I cannot find a way of formatting that time to something human like "26 December, 10:00".

我已经尝试了很多方法。
我不能使用 .strftime()、. strptime() nor dateutil.parser

I've tried alot of things.I cannot use .strftime(), .strptime()nordateutil.parser

最有前途的做法是:
变量= datetime.datetime.strptime(现在为'%Y-%m-%d%H:%M:%S。 %f')。strftime(%B%d,%Y),但随后出现此错误。.

The most promising this was doing:variable = datetime.datetime.strptime(now, '%Y-%m-%d %H:%M:%S.%f').strftime("%B %d, %Y") but then I get this error..

ValueError:time data'2018-12-13T11 :56:31.095470Z'与格式'%Y-%m-%d%H:%M:%S.%f'

ValueError: time data '2018-12-13T11:56:31.095470Z' does not match format '%Y-%m-%d %H:%M:%S.%f'

不匹配在互联网上,但我发现只有一个

I've searched on the internet but I've found just an 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'

然后使用以下命令打印事件。

print(stime, event['summary'])

这篇关于格式化Google日历活动日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 08:19