I fetch appointments via Exchange EWS API and create json arrays containing start/end busy (datetime) periods. I want to reverse this data to fetch a list of free time periods per day.
Office hours start is 8:00 a.m. Office hours end is 6:00 p.m.
Finally I found the solution for the arithmetic problem of how to calculate free time periods out of tuples of busy time periods. Below a simplified code how I did it.
from datetime import datetime, timedelta
import pprint
pp = pprint.PrettyPrinter()
tstart = datetime.strptime('08:00:00', '%H:%M:%S')
tstop = datetime.strptime('18:00:00', '%H:%M:%S')
appointments = ([
{
'start' : datetime.strptime('08:30:00', '%H:%M:%S'),
'end' : datetime.strptime('10:00:00', '%H:%M:%S')
},
{
'start' : datetime.strptime('09:30:00', '%H:%M:%S'),
'end' : datetime.strptime('11:00:00', '%H:%M:%S')
},
{
'start' : datetime.strptime('12:30:00', '%H:%M:%S'),
'end' : datetime.strptime('14:00:00', '%H:%M:%S')
},
{
'start' : datetime.strptime('15:30:00', '%H:%M:%S'),
'end' : datetime.strptime('16:00:00', '%H:%M:%S')
},
{
'start' : datetime.strptime('16:00:00', '%H:%M:%S'),
'end' : datetime.strptime('17:00:00', '%H:%M:%S')
},
])
"""
CORRECT FREE PERIODS ARE:
8:00 - 8:30
11:00 - 12:30
14:00 - 15:30
17:00 - 18:00
"""
tp = [(tstart , tstart)]
free_time = []
for t in appointments:
tp.append( ( t['start'] , t['end'] ) )
tp.append( (tstop , tstop) )
for i,v in enumerate(tp):
if i > 0:
if (tp[i][0] - tp[i-1][1]) > timedelta(seconds=0):
tf_start = tp[i-1][1]
delta = tp[i][0] - tp[i-1][1]
tf_end = tf_start + delta
free_time.append( (tf_start ,tf_end ) )
for tp in free_time:
print tp