有人可以帮助我让此脚本仅在指定时间范围内打印事件吗?

时间:2020-04-25 23:33:42

标签: python loops datetime

我在这里为datetime苦苦挣扎,让脚本只在指定时间内打印事件。我(现在)正在工作,但是需要让脚本遵守硬编码的时间,并且效果不佳

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 个答案:

答案 0 :(得分:0)

这是一种适合您需求的解决方案。

  1. 我们声明两个日期。 start_date,这是我们间隔的开始。 end_date,这是我们间隔的结束。

    • 我设置了适合我日历中几个事件的任意日期。您显然需要根据自己的需要进行设置。
    • 如果您想让end_date相对于start_date,可以查看如何在python中的日期时间对象中添加月份/天/小时/等。
  2. 对于收到的列表中的每个事件,我们将解析给出的日期字符串并将其存储在datetime_obj

    • Google提供的字符串将采用2020-10-202020-04-25T20:00:00-04:00的格式。对于第二个,我不确定结束-04:00是什么,因为这既不是示例事件的持续时间,也不是结束时间。因此,我将其截断并解析了字符串2020-04-25T20:00:00
  3. 现在,我们简单地检查在步骤2中计算的事件日期时间datetime_obj是否在步骤1 start_timeend_time中定义的两个日期之间。如果是这样,我们将打印事件。


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

参考:

  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