0

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

Shade Reogen
  • 136
  • 1
  • 12
  • By 'I cannot use .strftime(), .strptime()nordateutil.parser', do you mean you literally can't or you've not been successful using them? Then you show us a datetime.strptime example.. so I guess it's the latter. – ParvBanks Dec 13 '18 at 21:01
  • i've not been successful using them. Error says that "str" doesn't have object ".strftime" nor ".strptime" and so on – Shade Reogen Dec 13 '18 at 21:02
  • Can you try my answer.. and let me know if it works. Also, can you show us the result of `print(start)` to see what it returns. – ParvBanks Dec 13 '18 at 21:15

1 Answers1

2

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'])
ParvBanks
  • 1,138
  • 6
  • 15