How to return all events on a specific date in Google Calendar API

Question:

i am using Python and Google Calendar API to build a calendar.
I would like to get all the events that exist on a given date. The date will be given as a string ‘yyyy-mm-dd’.
I have created a function that does that but it is still returning the all-day events on the following day.

from datetime import *
import pytz

def get_events_by_date(api_service, event_date):

    split_date = event_date.split('-')

    event_date = datetime(int(split_date[0]), int(split_date[1]), int(split_date[2]), 00, 00, 00, 0)
    event_date = pytz.UTC.localize(event_date).isoformat()

    end = datetime(int(split_date[0]), int(split_date[1]), int(split_date[2]), 23, 59, 59, 999999)
    end = pytz.UTC.localize(end).isoformat()

    events_result = api_service.events().list(calendarId='primary', timeMin=event_date,timeMax=end).execute()
    return events_result.get('items', [])


>>all_events = get_events_by_date(api, '2022-09-24')
>>for event in all_events:
        print(event['summary'])

using this example, it prints all events on the ‘2022-09-24’ AND any all-day events on the ‘2022-09-25’. Any ideas why? (Or a better way to implement this feature)?

NOTE: i got the idea for the time zone conversion from this post Generate RFC 3339 timestamp in Python

Asked By: user19245296

||

Answers:

Although I’m not sure whether this is the direct solution to your issue, from your showing script, how about adding timeZone to the request as follows?

From:

events_result = api_service.events().list(calendarId='primary', timeMin=event_date,timeMax=end).execute()

To:

events_result = api_service.events().list(calendarId='primary', timeMin=event_date,timeMax=end, timeZone="UTC").execute()

Reference:

Answered By: Tanaike