Given two dates, our task is to write a Python program to get total business days, i.e weekdays between the two dates.
Example:
Input : test_date1, test_date2 = datetime(2015, 6, 3), datetime(2015, 7, 1)
Output : 20
Explanation : Total weekdays, i.e business days are 20 in span.
Input : test_date1, test_date2 = datetime(2015, 6, 3), datetime(2016, 7, 1)
Output : 282
Explanation : Total weekdays, i.e business days are 282 in span.
Method 1: Using timedelta() + sum() + weekday()
In this, all the dates are extracted using timedelta(), by incrementing differences till the end date. Post that, business days are filtered using weekday(), summing all which has a value less than 5. i.e Mon – Fri.
Python3
# Python3 code to demonstrate working of # Business days in range # Using timedelta() + sum() + weekday() from datetime import datetime, timedelta # initializing dates ranges test_date1, test_date2 = datetime( 2015 , 6 , 3 ), datetime( 2015 , 7 , 1 ) # printing dates print ( "The original range : " + str (test_date1) + " " + str (test_date2)) # generating dates dates = (test_date1 + timedelta(idx + 1 ) for idx in range ((test_date2 - test_date1).days)) # summing all weekdays res = sum ( 1 for day in dates if day.weekday() < 5 ) # printing print ( "Total business days in range : " + str (res)) |
Output:
The original range : 2015-06-03 00:00:00 2015-07-01 00:00:00 Total business days in range : 20
Time complexity : O(n)
Space Complexity : O(1)
Method #2 : Using np.busday_count()
This is inbuilt function that can be used to directly employ to solve this task.
Python3
# Python3 code to demonstrate working of # Business days in range # Using np.busday_count from datetime import datetime, timedelta import numpy as np # initializing dates ranges test_date1, test_date2 = datetime( 2015 , 6 , 3 ), datetime( 2015 , 7 , 1 ) # printing dates print ( "The original range : " + str (test_date1) + " " + str (test_date2)) # generating total days using busday_count() res = np.busday_count(test_date1.strftime( '%Y-%m-%d' ), test_date2.strftime( '%Y-%m-%d' )) # printing print ( "Total business days in range : " + str (res)) |
Output:
The original range : 2015-06-03 00:00:00 2015-07-01 00:00:00 Total business days in range : 20
Time complexity : O(1)
Space Complexity : O(1)
Method #3 : Using pandas.bdate_range()
This is another inbuilt function that can be used to directly employ to solve this task. Returns total business dates list inclusive of the start and end date.
Python3
# Python3 code to demonstrate working of # Business days in range # Using pd.bdate_range from datetime import datetime import pandas as pd # initializing dates ranges test_date1, test_date2 = datetime( 2015 , 6 , 3 ), datetime( 2015 , 6 , 30 ) # printing dates print ( "The original range : " + str (test_date1) + " " + str (test_date2)) # generating total days using pd.bdate_range() # len() gets the number of days # includes both last and first date. res = len (pd.bdate_range(test_date1.strftime( '%Y-%m-%d' ), test_date2.strftime( '%Y-%m-%d' ))) # printing result print ( "Total business days in range : " + str (res)) |
Output :
The original range : 2015-06-03 00:00:00 2015-06-30 00:00:00 Total business days in range : 20
Time complexity : O(n)
Space Complexity : O(n)
Method #4: Using a loop and weekday() function
- First, the program initializes two variables start_date and end_date as datetime objects with the date values of June 3, 2015 and June 30, 2015 respectively.
- Then, it initializes a variable num_business_days to 0 to keep count of the number of business days.
- Next, the program enters a while loop with the condition that the current_date is less than or equal to the end_date. The loop continues until it reaches the last date in the range.
- Inside the loop, the program checks if the current_date is a weekday (Monday to Friday) using the weekday() method. The method returns an integer representing the day of the week, where 0 is Monday and 6 is Sunday. If the weekday() value is less than 5, which represents a weekday, then the program increments the num_business_days variable by 1.
- The program then increments the current_date by one day using the timedelta function from the datetime module.
- The loop continues to iterate through each day in the date range until it reaches the end_date.
- Finally, the program prints the total number of business days between the two dates by displaying the value of num_business_days.
Python3
from datetime import datetime, timedelta # initializing dates ranges start_date, end_date = datetime( 2015 , 6 , 3 ), datetime( 2015 , 6 , 30 ) # initializing business days count num_business_days = 0 # looping through each day in the date range current_date = start_date while current_date < = end_date: # checking if the current day is a weekday if current_date.weekday() < 5 : num_business_days + = 1 # incrementing the current day by one day current_date + = timedelta(days = 1 ) # printing the result print ( "Total business days in range:" , num_business_days) |
Total business days in range: 20
Time complexity: O(n), where n is the number of days in the date range.
Auxiliary space: O(1), as we only need to keep track of one variable.
Method #5: Using numpy:
Algorithm:
- Initialize the start_date and end_date.
- Create a numpy array of dates using np.arange() function, which includes all the dates between the start_date and end_date.
- Convert the numpy array of dates to weekday numbers using np.datetime_as_string() and .astype() functions.
- Calculate the number of weekdays in the numpy array using np.count_nonzero() function.
- Print the total number of business days in the date range.
Python3
import numpy as np from datetime import datetime, timedelta # initializing dates ranges start_date, end_date = datetime( 2015 , 6 , 3 ), datetime( 2015 , 6 , 30 ) # creating an array of dates between the start and end dates dates = np.arange(start_date, end_date + timedelta(days = 1 ), dtype = 'datetime64[D]' ) # getting the weekday number for each date in the array weekday_num = np.datetime_as_string(dates, unit = 'D' ).astype( 'datetime64[D]' ).view( 'int' ) % 7 # counting the number of weekdays in the array num_business_days = np.count_nonzero((weekday_num < 5 )) # printing the result print ( "Total business days in range:" , num_business_days) #This code is contributed by vinay Pinjala. |
Output: Total business days in range: 20
Time complexity:
The np.arange() function takes O(1) time complexity.
The np.datetime_as_string() function takes O(n) time complexity, where n is the number of dates in the numpy array.
The .astype() function takes O(n) time complexity.
The np.count_nonzero() function takes O(n) time complexity.
Therefore, the overall time complexity of this algorithm is O(n).
Space complexity:
The np.arange() function creates a numpy array with a size of (end_date – start_date) + 1, which takes O(n) space complexity, where n is the number of dates in the numpy array.
The np.datetime_as_string() function creates a new numpy array of the same size, which takes O(n) space complexity.
The .astype() function creates a new numpy array of the same size, which takes O(n) space complexity.
The np.count_nonzero() function does not create any new array, so it takes O(1) space complexity.
Therefore, the overall space complexity of this algorithm is O(n).