Format Google Calendar Event Date

╄→尐↘猪︶ㄣ 提交于 2019-12-13 06:37:47

问题


Im working with the Python Google Calendar APi.

The Code:

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

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".

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

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


回答1:


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)

Output:

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

Then use the below command to print the event.

print(stime, event['summary'])


来源:https://stackoverflow.com/questions/53769739/format-google-calendar-event-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!