有一个网站已安排了一些活动,我能够将这些信息提取下来,进行解析并将其放入我的个人Google日历中。在将活动添加到Google日历之前,我想检查一下我的Google日历中是否存在具有相同标题和时间的活动。如果是,请跳过该事件。如果否,则将其发布。
我的想法是,我要抓住从今天开始的所有日期,并获得下一个X个事件,就像它在Google自己的Quickstart tutorial中的行为一样。然后,对于每个潜在的新事件,检查它是否与日历中已经存在的事件的日期,时间和描述相匹配。
这是我认为可以解决的问题,但没有[编辑更新代码]:
现在,即使时间未满,它也不会发布任何事件。
new_event = {
'summary': event_summary,
'location': event_location,
'description': '',
'start': {
'dateTime': event_start,
'timeZone': 'America/Chicago',
},
'end': {
'dateTime': event_end,
'timeZone': 'America/Chicago',
},
'reminders': {
'useDefault': True,
},
}
now = datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time
events_result = service.events().list(calendarId=calendar_ID,
timeMin=now,
maxResults=50, singleEvents=True,
orderBy='startTime').execute()
events = events_result.get('items', [])
for event in events:
start = event['start'].get('dateTime', event['start'].get('date'))
summary = event['summary']
if start == event_start and summary == event_summary:
break
else:
service.events().insert(calendarId=calendar_ID, body=new_event).execute()
任何帮助将不胜感激-我自学成才,因此我的知识和能力受到限制。
答案 0 :(得分:0)
我可以在一点帮助下解决问题:
使用:
new_event = {
'summary': event_summary,
'location': event_location,
'description': '',
'start': {
'dateTime': event_start,
'timeZone': 'America/Chicago',
},
'end': {
'dateTime': event_end,
'timeZone': 'America/Chicago',
},
'reminders': {
'useDefault': True,
},
}
这是代码:
class PostToGoogleCalendar:
def __init__(self):
self.creds = None
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
self.creds = pickle.load(token)
if not self.creds or not self.creds.valid:
if self.creds and self.creds.expired and self.creds.refresh_token:
self.creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
self.creds = flow.run_local_server()
with open('token.pickle', 'wb') as token:
pickle.dump(self.creds, token)
self.service = build('calendar', 'v3', credentials=self.creds)
def get_events(self):
now = datetime.utcnow().isoformat() + 'Z'
events_result = self.service.events().list(calendarId='primary', timeMin=now,
maxResults=500, singleEvents=True,
orderBy='startTime').execute()
return events_result.get('items', [])
def create_event(self, new_event):
if not self.already_exists(new_event):
event = self.service.events().insert(calendarId='primary', body=new_event).execute()
return event.get('htmlLink')
else:
return 'Event Already Exists'
def already_exists(self, new_event):
events = self.get_date_events(new_event['start']['dateTime'], self.get_events())
event_list = [new_event['summary'] for new_event in events]
if new_event['summary'] not in event_list:
return False
else:
return True
def get_date_events(self, date, events):
lst = []
date = date
for event in events:
if event.get('start').get('dateTime'):
d1 = event['start']['dateTime']
if d1 == date:
lst.append(event)
return lst