Skip to content

Instantly share code, notes, and snippets.

@dreispt
Last active December 28, 2015 23:39
Show Gist options
  • Save dreispt/7580893 to your computer and use it in GitHub Desktop.
Save dreispt/7580893 to your computer and use it in GitHub Desktop.
How many working hours from friday 16:30 to monday 15:30?
from datetime import time, datetime, timedelta
def working_hours(dt_start, dt_end, work_periods, work_days=range(5)):
dur = (dt_end.date() - dt_start.date()).days + 1
days = (dt_start.date() + timedelta(x) for x in range(dur))
return sum(
[(min(max(datetime.combine(d, h[1]), dt_start), dt_end) -
min(max(datetime.combine(d, h[0]), dt_start), dt_end)
).total_seconds()/3600
for d in days for h in work_periods
if d.weekday() in work_days])
if __name__ == '__main__':
work_periods = [(time(9), time(13)), (time(14, 30), time(18, 30))]
dt0 = datetime(2013, 11, 22, 16, 30) # Friday
dt1 = datetime(2013, 11, 25, 15, 30) # Monday
from pprint import pprint
print('%s -> %s:' % (dt0.isoformat(), dt1.isoformat()))
pprint(working_hours(dt0, dt1, work_periods))
@dreispt
Copy link
Author

dreispt commented Nov 21, 2013

Remove "sum" at line 11 to better see what's going on...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment