-
Notifications
You must be signed in to change notification settings - Fork 1
/
upload_to_calendar.py
95 lines (73 loc) · 2.89 KB
/
upload_to_calendar.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# https://developers.google.com/calendar/api/quickstart/python
import os.path
from os import environ
import time
import csv
from datetime import datetime, timedelta
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
almanac_cal_id = environ.get('ALMANAC_CAL_ID')
SCOPES = ['https://www.googleapis.com/auth/calendar']
creds = None
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
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)
with open('token.json', 'w') as token:
token.write(creds.to_json())
with open('data/celestial-almanac.csv', 'r') as infile:
reader = csv.DictReader(infile)
data = list(reader)
try:
service = build('calendar', 'v3', credentials=creds)
for ev in data:
title = ev.get('event_type')
start_datetime = datetime.fromisoformat(ev.get('datetime'))
all_day = ev.get('all_day')
if all_day:
start = {'date': start_datetime.date().isoformat()}
end = start
else:
start = {'dateTime': start_datetime.isoformat(timespec='seconds')}
# duration of lunar eclipse isn't available, so just add 60 mins
if 'lunar eclipse' in title:
end_dt = start_datetime + timedelta(minutes=60)
# solar eclipse data usually has duration values
if 'solar eclipse' in title:
seconds = ev.get('duration_seconds') or 0
minutes = ev.get('duration_minutes') or 0
total_duration = int(seconds) + (int(minutes) * 60)
# if no duration listed, make it 5 mins
if total_duration == 0:
total_duration = 5 * 60
end_dt = start_datetime + timedelta(seconds=total_duration)
end = {'dateTime': end_dt.isoformat(timespec='seconds')}
event = {
'summary': ev.get('event_type'),
'start': start,
'end': end,
'reminders': {
'useDefault': False,
'overrides': [
{'method': 'email', 'minutes': 24 * 60}
],
},
}
e = service.events().insert(
calendarId=almanac_cal_id,
body=event
).execute(num_retries=50)
link = e.get('htmlLink')
print(f'{ev.get("datetime")} - {ev.get("event_type")}')
print(f' Event created: {link}')
time.sleep(0.5)
except HttpError as error:
print(f'An error occurred: {error}')