Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
date time timedelta solution in Clear category for Working Hours Calculator by Phil15
from datetime import date, time, timedelta
def delta_hours(start: time, end: time) -> float:
# I still do not know why we can't do `end - start` and get a timedelta on which we could do `.total_seconds()`.
return (
end.hour - start.hour
+ (end.minute - start.minute) / 60 # I know, minutes are all zeros at the time I write this.
+ (end.second - start.second) / 60 / 60 # I know, there is not any second at the time I write this.
)
def working_hours(
start_date: str,
end_date: str,
start_time: str,
end_time: str,
holy: list[str],
) -> float:
# First convert to types we can actually use.
d = date.fromisoformat(start_date)
end_date = date.fromisoformat(end_date)
holy = frozenset(map(date.fromisoformat, holy))
hours_by_day = delta_hours(time.fromisoformat(start_time), time.fromisoformat(end_time))
# Now we can count.
one_day = timedelta(1)
working_days = 0
while d <= end_date:
# 0 monday, ... 5 saturday, 6 sunday
if d.weekday() < 5 and d not in holy:
working_days += 1
d += one_day
return working_days * hours_by_day
March 2, 2023