Maintenance

Site is under maintenance — quizzes are still available.

Go to quizzes
Sponsored Reserved space — layout preview until AdSense is connected

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.

Medium Python 3.9+ Jun 28, 2026 Files & data 2 views 0 copies

Python code

24 lines
Python 3.9+
from 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

stdout
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

  1. Use `pandas.bdate_range` with custom business hours for DataFrame-based time series.
  2. 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

Sponsored Reserved space — layout preview until AdSense is connected

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Files & data

Related tutorials and quizzes for this topic.