0

I am struggling with datetime in here and getting the script to only print events during a specified time. I have (now) working but need to have the script adhere to a hardcoded time and that isn't working well

from __future__ import print_function
import datetime
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

# If modifying these scopes, delete the file token.pickle.
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.
    """
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('calendar', 'v3', credentials=creds)

    # Call the Calendar API
    now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time
    events_result = service.events().list(calendarId='primary', timeMin=now, 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()

1 Answers1

0

Here is a solution that should fit your needs.

  1. We declare two dates. start_date which is the beginning of our interval. end_date which is the ending of our interval.

    • I have set arbitrary dates that fit a couple of events in my calendar. You would obviously need to set these according to your needs.
    • If you want to have end_date relative to start_date, you can look at how to add months/days/hours/etc to a datetime object in python.
  2. For each event in the list we received, we will parse the date string given and store it in datetime_obj

    • The string given by google will either be in the format 2020-10-20 or 2020-04-25T20:00:00-04:00. For the second one, I am not sure what the ending -04:00 is as that is not the duration of my sample event nor the ending time. So I truncated that part and parsed the string 2020-04-25T20:00:00
  3. Now we simply check if the event datetime datetime_obj we calculated in step 2 is between the two dates we defined in step 1 start_time and end_time. If it is, we print the event.


start_time = datetime.datetime(2020, 4, 20, 12, 0, 0)
end_time = datetime.datetime(2020, 4, 29, 12, 0, 0)

if not events:
    print('No upcoming events found.')
for event in events:
    start = event['start'].get('dateTime', event['start'].get('date'))
    if (len(start) > 19):
        datetime_obj = datetime.datetime.strptime(start[:-6], '%Y-%m-%dT%H:%M:%S')
    else:
        datetime_obj = datetime.datetime.strptime(start, '%Y-%m-%d')

    if (start_time < datetime_obj < end_time):
        print(datetime_obj.strftime("%Y-%m-%dT%H:%M:%S"))
        print(start, event['summary'])

References:

  1. https://strftime.org/
  2. https://developers.google.com/calendar/quickstart/python
  3. How to tell if a date is between two other dates in Python?
  4. Converting string into datetime
  5. Convert datetime object to a String of date only in Python
Sri
  • 2,281
  • 2
  • 17
  • 24