简体   繁体   中英

Get Number of working days per month in Python

Hello world,

I would like to retrieve for each month the number of working days.

Here is my dataset

City       date        value   End_date
Berlin     01/01/16    41       31/01/16
Munich     01/10/16    74       31/10/16
Dresden    01/05/16    97       31/05/16

With the following Code, I am able to retrieve the number of working day per month manually:

from datetime import datetime
from workalendar.europe.germany import Germany

start_date = "2020-12-01"
end_date = "2020-12-31"

start_datetime = datetime.strptime(start_date, '%Y-%m-%d')
end_datetime = datetime.strptime(end_date, '%Y-%m-%d')

cal = Germany()

print(cal.get_working_days_delta(start_datetime, end_datetime))

out:
21

The Question: How can I store the value for each month and year(2016 to 2022) within the dataframe?

Expected output

City       date        value   End_date    Nb_working_days
Berlin     01/01/16    41       31/01/16        20
Munich     01/10/16    74       31/10/16        20
Dresden    01/05/16    97       31/05/16        20

Convert both columns to datetimes by to_datetime and then use lambda function by DataFrame.apply :

from workalendar.europe.germany import Germany
cal = Germany()

df['date'] = pd.to_datetime(df['date'], format='%d/%m/%y')
df['End_date'] = pd.to_datetime(df['End_date'], format='%d/%m/%y')

f = lambda x: cal.get_working_days_delta(x['date'], x['End_date'])
df['Nb_working_days'] = df.apply(f, axis=1)
print (df)
      City       date  value   End_date  Nb_working_days
0   Berlin 2016-01-01     41 2016-01-31               20
1   Munich 2016-10-01     74 2016-10-31               20
2  Dresden 2016-05-01     97 2016-05-31               20

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM