Python Program to Get total Business days between two dates
Last Updated :
26 Apr, 2023
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
from datetime import datetime, timedelta
test_date1, test_date2 = datetime( 2015 , 6 , 3 ), datetime( 2015 , 7 , 1 )
print ( "The original range : " + str (test_date1) + " " + str (test_date2))
dates = (test_date1 + timedelta(idx + 1 )
for idx in range ((test_date2 - test_date1).days))
res = sum ( 1 for day in dates if day.weekday() < 5 )
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
from datetime import datetime, timedelta
import numpy as np
test_date1, test_date2 = datetime( 2015 , 6 , 3 ), datetime( 2015 , 7 , 1 )
print ( "The original range : " + str (test_date1) + " " + str (test_date2))
res = np.busday_count(test_date1.strftime( '%Y-%m-%d' ),
test_date2.strftime( '%Y-%m-%d' ))
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
from datetime import datetime
import pandas as pd
test_date1, test_date2 = datetime( 2015 , 6 , 3 ), datetime( 2015 , 6 , 30 )
print ( "The original range : " + str (test_date1) + " " + str (test_date2))
res = len (pd.bdate_range(test_date1.strftime( '%Y-%m-%d' ),
test_date2.strftime( '%Y-%m-%d' )))
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
start_date, end_date = datetime( 2015 , 6 , 3 ), datetime( 2015 , 6 , 30 )
num_business_days = 0
current_date = start_date
while current_date < = end_date:
if current_date.weekday() < 5 :
num_business_days + = 1
current_date + = timedelta(days = 1 )
print ( "Total business days in range:" , num_business_days)
|
Output
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
start_date, end_date = datetime( 2015 , 6 , 3 ), datetime( 2015 , 6 , 30 )
dates = np.arange(start_date, end_date + timedelta(days = 1 ), dtype = 'datetime64[D]' )
weekday_num = np.datetime_as_string(dates, unit = 'D' ).astype( 'datetime64[D]' ).view( 'int' ) % 7
num_business_days = np.count_nonzero((weekday_num < 5 ))
print ( "Total business days in range:" , num_business_days)
|
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).
Similar Reads
Python program to find number of days between two given dates
Given two dates, Write a Python program to find the total number of days between them. Examples: Input : dt1 = 13/12/2018, dt2 = 25/2/2019Output : 74 daysInput : dt1 = 01/01/2004, dt2 = 01/01/2005Output : 366 days Naive Approach: One Naive Solution is to start from dt1 and keep counting the days til
5 min read
Python - Generate k random dates between two other dates
Given two dates, the task is to write a Python program to get K dates randomly. Input : test_date1, test_date2 = date(2015, 6, 3), date(2015, 7, 1), K = 7 Output : [datetime.date(2015, 6, 18), datetime.date(2015, 6, 25), datetime.date(2015, 6, 29), datetime.date(2015, 6, 11), datetime.date(2015, 6,
4 min read
Python program to find day of the week for a given date
Write a Python program to extract weekdays from a given date for any particular date in the past or future. Let the input be in the format "dd mm yyyy". Example Input : 03 02 1997 Output : MondayInput : 31 01 2019Output : ThursdayThe already discussed approach to extract weekdays from a given date f
6 min read
Python program to get the nth weekday after a given date
Given a date and weekday index, the task is to write a Python program to get the date for the given day of the week occurring after the given date. The weekday index is based on the below table: IndexWeekday0Monday1Tuesday2Wednesday3Thursday4Friday5Saturday6Sunday Examples: Input : test_date = datet
3 min read
Python Program to Print the Incremented Date if valid
In this article, we will write a python program to input a date and check whether it is a valid date or not. If it is valid, output the incremented date. Otherwise, print âInvalid dateâ. Examples: Input : 1/2/2000 Output: 2/2/2000 Input : 29/2/2002 Output: Invalid date Input : 31/12/2015 Output: 1/1
3 min read
Python Program to check date in date range
Given a date list and date range, the task is to write a Python program to check whether any date exists in the list in a given range. Example: Input : test_list = [datetime(2019, 12, 30), datetime(2018, 4, 4), datetime(2016, 12, 21), datetime(2021, 2, 2), datetime(2020, 2, 3), datetime(2017, 1, 1)]
10 min read
Python program to find birthdate on the same day you were born
Write a program to find birthdates till a given year on the same day you were born. Let the input be of the format: YYYY-MM-DDExamples: Input: 1996-11-12 Output: ['1996-11-12', '2002-11-12', '2013-11-12', '2019-11-12', '2024-11-12', '2030-11-12', '2041-11-12', '2047-11-12'] Input: 1992-11-2 Output:
3 min read
Python program to find Last date of Month
Given a datetime object, the task is to write a Python Program to compute the last date of datetime object Month. Examples: Input : test_date = datetime.datetime(2018, 6, 4) Output : 30 Explanation : April has 30 days, each year Input : test_date = datetime.datetime(2020, 2, 4) Output : 29 Explanati
3 min read
Python program to print current year, month and day
In this article, the task is to write a Python Program to print the current year, month, and day. Approach: In Python, in order to print the current date consisting of a year, month, and day, it has a module named datetime. From the DateTime module, import date classCreate an object of the date clas
1 min read
Python - Get Most recent previous business day
Given a date, the task is to write a Python program to get the most recent previous business day from the given date. Example: Input : test_date = datetime(2020, 1, 31) Output : 2020-01-30 00:00:00 Explanation : 31 Jan 2020, being a Friday, last business day is thursday, i.e 30 January. Input : test
4 min read