Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate difference between two dates excluding weekends in python?

I want to create function which return me the difference between two dates excluding weekends and holidays ?

Eg:- Difference between 01/07/2019 and 08/07/2019 should return me 5 days excluding (weekend on 6/7/107 and 7/07/2019).

What should be best possible way to achieve this ???

like image 964
Paras Ghai Avatar asked Mar 03 '23 16:03

Paras Ghai


1 Answers

Try converting string into date using the format of your date using pd.to_datetime()

use np.busday_count to find difference between days excluding the weekends

import pandas as pd
import numpy as np

date1 = "01/07/2019"
date2 = "08/07/2019"

date1 = pd.to_datetime(date1,format="%d/%m/%Y").date()
date2 = pd.to_datetime(date2,format="%d/%m/%Y").date()

days = np.busday_count( date1 , date2)
print(days)
5

incase you want to provide holidays

holidays = pd.to_datetime("04/07/2019",format="%d/%m/%Y").date()
days = np.busday_count( start, end,holidays=[holidays] )
print(days)
4
like image 57
tawab_shakeel Avatar answered Apr 28 '23 05:04

tawab_shakeel