Skip to content

Instantly share code, notes, and snippets.

@darrensapalo
Created April 12, 2016 16:09
Show Gist options
  • Save darrensapalo/d15d1fde9943c012177f39b4588fbc98 to your computer and use it in GitHub Desktop.
Save darrensapalo/d15d1fde9943c012177f39b4588fbc98 to your computer and use it in GitHub Desktop.
Acquire the entries in my google calendar that are related to our family driver, to compute for his over time.
from __future__ import print_function
import httplib2
import os
from apiclient import discovery
import oauth2client
from oauth2client import client
from oauth2client import tools
import datetime
import iso8601
import time
try:
import argparse
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
flags = None
# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/calendar-python-quickstart.json
SCOPES = 'https://www.googleapis.com/auth/calendar.readonly'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Google Calendar API Python Quickstart'
def get_credentials():
"""Gets valid user credentials from storage.
If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.
Returns:
Credentials, the obtained credential.
"""
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir,
'calendar-python-quickstart.json')
store = oauth2client.file.Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
flow.user_agent = APPLICATION_NAME
if flags:
credentials = tools.run_flow(flow, store, flags)
else: # Needed only for compatibility with Python 2.6
credentials = tools.run(flow, store)
print('Storing credentials to ' + credential_path)
return credentials
def isRelatedToKuyaJerry(event):
return 'Jerry' in event['summary']
def isDriving(event):
return 'overtime' not in event['summary'] or 'drives me' in event['summary']
def main():
"""Fetches the number of times our family driver, Kuya Jerry has
performed over time work based on my Google Calendar entries.
Over time work is defined to be work outside his work schedule of
7AM-4PM.
"""
os.environ['TZ'] = 'Asia/Manila'
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('calendar', 'v3', http=http)
now = datetime.datetime.utcnow()
month = now.strftime('%B')
minimum = datetime.datetime(now.year, now.month, 1, 0, 0, 0).isoformat() + 'Z' # 'Z' indicates UTC time
now = datetime.datetime.now()
filename = month + ' ' + str(now.year) + '.report'
file = open('./' + filename, 'w+')
file.write('Getting Kuya Jerry\'s overtime from my Google Calendar\n')
file.write(month + ' ' + str(now.year) + '\n')
file.write('\n')
eventsResult = service.events().list(
calendarId='primary', timeMin=minimum, singleEvents=True,
orderBy='startTime').execute()
events = eventsResult.get('items', [])
events = [e for e in events if isRelatedToKuyaJerry(e) and isDriving(e)]
totalMinutes = 0
if not events:
file.write('No events found. \n')
for event in events:
start = event['start']['dateTime']
startDt = iso8601.parse_date(start)
startString = startDt.strftime('%b %d - %I:%M %p')
end = event['end']['dateTime']
endDt = iso8601.parse_date(end)
endString = endDt.strftime('%b %d - %I:%M %p')
d1_ts = time.mktime(startDt.timetuple())
d2_ts = time.mktime(endDt.timetuple())
minutes = int(d2_ts-d1_ts) / 60
file.write(startString + ' ' + endString + '\n')
file.write(str(minutes) + ' minutes' + ' ' + event['summary'] + '\n')
file.write('\n')
totalMinutes += minutes
totalHours = totalMinutes / 60
totalMinutes = totalMinutes % 60
file.write('Total amount of overtime: ' + str(totalHours) + 'h ' + str(totalMinutes) + 'm' + '\n')
file.write('Report generated on ' + now.strftime('%b %d - %I:%M %p') + '\n')
file.write('\n')
print("Report generated: " + filename)
print()
print('Total amount of overtime: ' + str(totalHours) + 'h ' + str(totalMinutes) + 'm')
print('Report generated on ' + now.strftime('%b %d - %I:%M %p'))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment