[python] 파이썬 workalendar를 사용하여 특정 날짜의 공휴일이 포함되는 주말과 주말이 아닌 날짜의 개수 계산하기

파이썬에서는 workalendar라는 라이브러리를 사용하여 특정 날짜의 공휴일이 포함되는 주말과 주말이 아닌 날짜의 개수를 간단하게 계산할 수 있습니다. workalendar는 다양한 국가의 공휴일 정보를 제공하며, 여기서는 한국의 공휴일 정보를 사용해 예시를 보여드리겠습니다.

workalendar 설치하기

먼저, workalendar를 설치해야 합니다. 아래의 명령어를 사용하여 파이썬 패키지 매니저인 pip를 통해 workalendar를 설치할 수 있습니다.

pip install workalendar

코드 예시

다음은 workalendar를 사용하여 특정 날짜의 공휴일이 포함되는 주말과 주말이 아닌 날짜의 개수를 계산하는 코드의 예시입니다.

from workalendar.asia import SouthKorea
from datetime import date, timedelta

def count_weekend_and_non_weekend_dates_with_holidays(start_date, end_date):
    cal = SouthKorea()
    holidays = cal.holidays(start_date.year, end_date.year)
    weekend_count = 0
    non_weekend_count = 0

    current_date = start_date
    while current_date <= end_date:
        if current_date.weekday() in [5, 6] and current_date not in holidays:
            weekend_count += 1
        elif current_date.weekday() not in [5, 6] and current_date not in holidays:
            non_weekend_count += 1
        current_date += timedelta(days=1)

    return weekend_count, non_weekend_count

start_date = date(2022, 1, 1)
end_date = date(2022, 12, 31)

weekend_count, non_weekend_count = count_weekend_and_non_weekend_dates_with_holidays(start_date, end_date)

print("주말 개수:", weekend_count)
print("주말이 아닌 날짜 개수:", non_weekend_count)

위의 코드에서는 workalendar.asia 모듈에서 SouthKorea 클래스를 import하여 한국의 공휴일 정보를 사용하고, date 객체를 사용하여 시작 날짜와 종료 날짜를 설정합니다. count_weekend_and_non_weekend_dates_with_holidays 함수에서는 주말과 주말이 아닌 날짜의 개수를 계산하는 로직을 구현합니다. 이후에는 예시로 주어진 2022년 1월 1일부터 12월 31일까지의 주말 개수와 주말이 아닌 날짜 개수를 계산하고 결과를 출력합니다.

참고 자료