1

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

  • Although I'm not sure whether this is the direct solution to your issue, I proposed a modification point as an answer. Could you please confirm it? If that was not the direct solution of your issue, I apologize. – Tanaike Sep 23 '22 at 03:13

1 Answers1

2

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:

Tanaike
  • 181,128
  • 11
  • 97
  • 165
  • Yes! that solved the issue! Thanks so much...can you please explain what the issue was and how it solved it? – user19245296 Sep 23 '22 at 03:30
  • @user19245296 Thank you for replying. I'm glad your issue was resolved. About `timeZone`, when I saw the official document, it says `Time zone used in the response. Optional. The default is the time zone of the calendar.`. From this and your script, I thought that when `timeZone` is set like `timeZone="UTC"`, it might be a solution of your issue. If this explanation was not useful, I apologize. – Tanaike Sep 23 '22 at 05:51