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)
```
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)
```
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!
An additional library is needed for my answer (NumPy)
Key elements:
Steps:
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
This will do it:
busdays = np.busday_count(start_time.date(), end_time.date())
I came up with this, it only uses the datetime module:
import datetime
def hours_between_dates(start_datetime):
today_dt = datetime.datetime.now()
#calculate the total age in hours
alltime = today_dt - start_datetime
hour_alltime = alltime.total_seconds() / 3600
#if the start date is on the weekend the count starts on the next monday
if start_datetime.weekday() == 5:
start_datetime += datetime.timedelta(days=2)
elif start_datetime.weekday() == 6:
start_datetime += datetime.timedelta(days=1)
#iteratinng through the days between the start date and the actual date
#if the day is a weekend day, it subtracts 24 hours from the total time
while start_datetime.date() != today_dt.date():
if start_datetime.weekday() == 5 or start_datetime.weekday() == 6:
hour_alltime -= 24
start_datetime += datetime.timedelta(days=1)
return round(hour_alltime, 2)