1

I want total number of hours between mention dates excluding weekend(Saturday, Sunday).

```
start_time = datetime.datetime(2021, 7, 1, 22, 45, 25)
end_time = datetime.datetime(2021, 7, 15, 10, 00, 00)
```
hardik patel
  • 134
  • 1
  • 8
  • 1
    This might be useful: https://stackoverflow.com/questions/3615375/number-of-days-between-2-dates-excluding-weekends – antun Jul 01 '21 at 17:35

3 Answers3

1

An additional library is needed for my answer (NumPy)

Key elements:

  1. numpy.busday_count to count the number of weekdays
  2. datetime.timedelta(1) to omit starting day (to be checked through if-else to count for minutes)
  3. isoweekday() returns value between 1 and 7, 1 being Monday and 7 Sunday

Steps:

  1. Skip the starting and ending days and find valid in-between days. Multiply by 24 (total hours per day)
  2. Check if starting day is a weekday and calculate the total hours remaining to end that date
  3. Check if the ending day is a weekday and calculate the total hours passed in that day
import datetime
import numpy as np

start_time = datetime.datetime(2021, 7, 1, 22, 45, 25)
end_time = datetime.datetime(2021, 7, 15, 10, 00, 00)
#Step 1.
total_hours=np.busday_count(start_time.date()+datetime.timedelta(1),end_time.date())*24 #already not counting last date
#Step2.
if start_time.isoweekday() in range(1, 6):
    total_hours=total_hours+24-start_time.hour-start_time.minute/60-start_time.second/3600
#Step 3.
if end_time.isoweekday() in range(1, 6):
    total_hours=total_hours+end_time.hour+end_time.minute/60+end_time.second/3600
print(total_hours)
output: 227.24305555555554
1
from BusinessHours import BusinessHours
import datetime

start_time = datetime.datetime(2021, 7, 1, 22, 45, 25)
end_time = datetime.datetime(2021, 7, 15, 10, 00, 00)

hours = BusinessHours(start_time, end_time, worktiming=[9, 18], weekends=[6, 7], holidayfile=None)
print(hours.gethours())

This could help you, for more information please refer BusinessHours module in python!

Akshay Reddy
  • 73
  • 2
  • 10
0

This will do it:

busdays = np.busday_count(start_time.date(), end_time.date())
pedro_bb7
  • 996
  • 2
  • 8
  • 22