Calculate Working Hours Between Two Dates in Python
Compute total business hours (Mon-Fri, 09:00-17:00) between two datetime objects, excluding weekends and non-working hours.
Python code
24 linesfrom datetime import datetime, timedelta
def work_hours_between(start: datetime, end: datetime) -> float:
"""Calculate total working hours between two datetimes (Mon-Fri, 09:00-17:00)."""
def is_workday(d: datetime) -> bool:
return d.weekday() < 5
total_hours = 0.0
current = start
while current.date() <= end.date():
if is_workday(current):
day_start = current.replace(hour=9, minute=0, second=0, microsecond=0)
day_end = current.replace(hour=17, minute=0, second=0, microsecond=0)
effective_start = max(current, day_start)
effective_end = min(end, day_end) if current.date() == end.date() else day_end
if effective_start < effective_end:
total_hours += (effective_end - effective_start).total_seconds() / 3600
current += timedelta(days=1)
return total_hours
if __name__ == "__main__":
start = datetime(2025, 1, 13, 10, 30) # Monday
end = datetime(2025, 1, 17, 14, 15) # Friday
print(f"{work_hours_between(start, end):.2f}")
Output
30.75
How it works
The function iterates day by day from start to end, checking each day with weekday() < 5 to skip weekends. For each workday, it defines the standard 09:00-17:00 window but clips to the actual start and end times on the boundary days. It sums the effective working hours as floating-point hours using total_seconds() / 3600. This approach handles partial days and multi-week spans correctly without requiring external libraries.
Common mistakes
- Forgetting to handle the end date's time within the same day (using `min`).
- Not resetting microsecond and second for day_start/day_end, causing subtle rounding issues.
- Assuming the start and end dates are always within the same work week.
- Using integer division instead of `total_seconds()` to compute fractional hours.
Variations
- Use `pandas.bdate_range` with custom business hours for DataFrame-based time series.
- Implement with `numpy.busday_count` and a timedelta adjustment for fractional days.
Real-world use cases
- Generate accurate invoices for hourly consulting work spanning several days.
- Calculate employee attendance or overtime within a standard 9-to-5 work week.
- Measure SLA response time excluding weekends and after-hours in support tickets.
Sponsored
More from Files & data
- Audit File Permissions Across a Project in Python easy
- Automatically Detect Corrupted Files Using SHA-256 Checksums in Python easy
- Automatically Highlight Data Validation Errors Inside Excel Files in Python easy
- Build a Command-Line To-Do List Application with Data Persistence in Python easy
- Build a Personal Work Hours Tracker in Python medium
- Build a Python Script That Detects and Deletes Empty Files Across Folders easy
Keep learning
Related tutorials and quizzes for this topic.