月ごとの営業日数を求めたい事があったので、pythonで簡単にやってみた。
祝日計算
祝日計算には内閣府のcsvファイルを取ってくる方法を見つけた*1が、これだと振替休日などに対応できない。
そこで、こちらで紹介されているjpholidayを使った。
github.com
コード
実行前に
pip install jpholiday
としてjpholidayを取ってくる必要がある
import datetime, jpholiday def is_holiday_or_weekend(date): return date.weekday() == 6 or date.weekday() == 5 or jpholiday.is_holiday(date) def businessday_count(year, month): date = datetime.date(year, month, 1) sum = 0 while month == date.month: if not is_holiday_or_weekend(date): sum += 1 date = date + datetime.timedelta(1) return sum if __name__=="__main__": year = 2019 for i in range(1,13): print(i,end="\t") print(businessday_count(year, i))
結果
1 21 2 19 3 20 4 20 5 19 6 20 7 22 8 21 9 19 10 21 11 20 12 22
おまけ
月の末日を取ってくる
python - Get the last day of the month - Stack Overflow
monthrange(year, month) Returns weekday of first day of the month and number of days in month, for the specified year and month.
>>> import calendar >>> calendar.monthrange(2002,1) (1, 31) >>> calendar.monthrange(2008,2) (4, 29) >>> calendar.monthrange(2100,2) (0, 28)