7

I want to calculate the difference between the two dates but want to exclude the weekends from it . Below is the format of dates :

CreateDate  - 2017-08-29 10:47:00
ResolveDate - 2017-09-23 16:56:00
vikrant rana
  • 4,509
  • 6
  • 32
  • 72
Karan Khanna
  • 117
  • 1
  • 1
  • 6

5 Answers5

7

You can use numpy.busday_count:

from datetime import datetime
import numpy as np

create_date = "2017-08-29 10:47:00"
resolve_date = "2017-09-23 16:56:00"

create_datetime = datetime.strptime(create_date, '%Y-%m-%d %H:%M:%S')
resolve_datetime = datetime.strptime(resolve_date, '%Y-%m-%d %H:%M:%S')

print(f"The difference in days is: {(resolve_datetime - create_datetime).days}")
print(f"The difference in business days is: {np.busday_count(create_datetime.date(), resolve_datetime.date())}")

Output:

The difference in days is: 25
The difference in business days is: 19
Sash Sinha
  • 18,743
  • 3
  • 23
  • 40
4

One more python way using isoweekday():

import datetime, pprint

# isoweekday: Monday is 1 and Sunday is 7
start_date = datetime.date(2017, 10, 1)
end_date = datetime.date(2017, 12, 31)
days = end_date - start_date
valid_date_list = {(start_date + datetime.timedelta(days=x)).strftime('%d-%b-%Y')
                        for x in range(days.days+1)
                        if (start_date + datetime.timedelta(days=x)).isoweekday() <= 5
                       }
print("Business Days = {}".format(len(valid_date_list)))
Vikas
  • 41
  • 1
1

Run a while loop that keeps adding a timedelta of +1 day to create_date. Keep track of weekday vs. weekend in a separate counter.

J_H
  • 17,926
  • 4
  • 24
  • 44
0

Same idea with weekday() but as a one-line function:

from datetime import datetime, timedelta


def get_business_days(start_date, end_date):
    return sum([
        (start_date + timedelta(days=i)).weekday() not in (5, 6)
        for i in range((end_date - start_date).days + 1)
    ])


create_date = "2017-08-29 10:47:00"
resolve_date = "2017-09-23 16:56:00"

s = datetime.strptime(create_date, '%Y-%m-%d %H:%M:%S')
e = datetime.strptime(resolve_date, '%Y-%m-%d %H:%M:%S')

print(get_business_days(s, e))
Yann
  • 2,426
  • 1
  • 16
  • 33
-1

With datetime module:

import datetime

d1 = datetime.datetime.strptime('2017-08-29 10:47:00', '%Y-%m-%d %H:%M:%S')
d2 = datetime.datetime.strptime('2017-09-23 16:56:00', '%Y-%m-%d %H:%M:%S')
delta = (d2 - d1).days
diff_weekdays = delta - (delta // 7) * 2

print(diff_weekdays)    # 19
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
  • How can i get exact hours diff from this (excluding weekend days and holidays ) – Rahul Aug 23 '19 at 01:04
  • This solution doesn't work as expected, because it assumes the start date is at the beginning of the week. If the start date is e.g. this friday, and the end date is the next monday, the result will be 3, because of the way transcurred weeks are calculated (3 // 7 = 0). – Luisg123v Jan 18 '20 at 01:12