Skip to content

Instantly share code, notes, and snippets.

@dpinney
Created January 9, 2021 21:35
Show Gist options
  • Save dpinney/f430cf34ad46b25521fae17c353f6902 to your computer and use it in GitHub Desktop.
Save dpinney/f430cf34ad46b25521fae17c353f6902 to your computer and use it in GitHub Desktop.
Get all free times from iCal on the Command Line
'''
Get all free times from iCal.
Requirements:
brew install ical-buddy
pip install py-dateutil
Notes:
Run in terminal because it needs calendar permissions.
This only handles hourly blocks. I.e. if 30 minutes is filled, we call the entire hour filled.
Ignores all-day events.
'''
import subprocess
from datetime import datetime as dt
from datetime import timedelta as td
import os
# Options
WORK_HOURS = set(range(10,17+1)) # 10 am to 6 pm
DAYS_AHEAD = 7
SKIP_WEEKENDS = True
NO_MILITARY_TIME = True
# Constants
date_format = '%Y-%m-%d'
now = dt.now()
now_date = now.strftime(date_format)
def to_12(t24):
if t24 < 12:
return f'{t24} AM'
elif t24 == 12:
return f'{t24} AM'
else:
return f'{t24-12} PM'
# Get Free Times
print(f'My free times over the next {DAYS_AHEAD} work days:\n')
i = 0
max_days = DAYS_AHEAD
while i < max_days:
curr_day = now + td(days=i)
if SKIP_WEEKENDS and curr_day.weekday() >= 5:
max_days = max_days + 1
i = i + 1
continue
just_date = curr_day.strftime(date_format)
print(curr_day.strftime(date_format + ' (%a)'))
raw_events = subprocess.check_output(f'icalBuddy -nrd -sed --timeFormat %H -df "" -b "" -iep datetime eventsFrom:{just_date} to:{just_date}', shell=True)
out_str = raw_events.decode("utf-8")
nice_data = [x.split(' - ') for x in out_str.split('\n') if len(x) != 0]
nicer_data = [[int(x[0]),int(x[1])] if x[0] != x[1] else [int(x[0]),int(x[0]) + 1] for x in nice_data]
nicest_data = [list(range(x[0],x[1])) for x in nicer_data]
occupied_hours = set([x for sublist in nicest_data for x in sublist])
free_hours = WORK_HOURS if len(occupied_hours) == 0 else WORK_HOURS - occupied_hours
if NO_MILITARY_TIME:
free_hours = [to_12(x) for x in sorted(free_hours)]
nice_out = 'None\n' if len(free_hours) == 0 else ', '.join(free_hours) + '\n'
print(nice_out)
i = i + 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment