Write a Python function to calculate the total number of business days from a range of start and end date


Assume, you have a date_range of dates and the result for the total number of business days are,

Dates are:
DatetimeIndex(['2020-01-01', '2020-01-02', '2020-01-03', '2020-01-06',
               '2020-01-07', '2020-01-08', '2020-01-09', '2020-01-10',
               '2020-01-13', '2020-01-14', '2020-01-15', '2020-01-16',
               '2020-01-17', '2020-01-20', '2020-01-21', '2020-01-22',
               '2020-01-23', '2020-01-24', '2020-01-27', '2020-01-28',
               '2020-01-29', '2020-01-30', '2020-01-31'],
               dtype='datetime64[ns]', freq='B')
Total number of days: 23

Solution 1

  • Define a function as business_days()

  • set pd.bdate_range() function start value as ‘2020-01-01’ and end as ‘2020-02-02’ and save it as dates,

dates = pd.bdate_range('2020-01-01','2020-02-02')
  • Calculate the number of days using len(dates)

len(dates)

Example

Let’s check the following code to get a better understanding −

import pandas as pd
def business_days():
   dates = pd.bdate_range('2020-01-01','2020-02-02')
   print("Total number of days:",len(dates))
business_days()

Output

Total number of days: 23

Solution 2

  • Define a function

  • set pd.bdate_range() function start value as ‘2020-01-01’ and end as ‘2020-02-02’ and save it as dates,

dates = pd.bdate_range('2020-01-01','2020-02-02')
  • Set count as 0 and create for loop to access all the values from dates and increment the count value itself by 1

count = 0
   for i in dates:
      count = count + 1
  • Finally, print the count.

Example

import pandas as pd
def business_days():
   dates = pd.bdate_range('2020-01-01','2020-02-02')
   count = 0
   for i in dates:
      count = count + 1
   print("Total number of days:",count)
business_days()

Output

Total number of days: 23

Updated on: 25-Feb-2021

330 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements