[python] 파이썬 workalendar를 사용하여 특정 날짜의 이전/다음 휴일 혹은 주말이 포함되는 휴일 사이의 모든 날짜 가져오기

프로젝트를 진행하다보면, 특정 날짜의 이전 혹은 다음 휴일을 구하거나, 주말이 포함되는 휴일 사이의 모든 날짜를 필요로 할 때가 있습니다. 이런 경우에는 파이썬의 workalendar 라이브러리를 사용하면 편리하게 작업할 수 있습니다.

workalendar 설치하기

먼저, workalendar를 설치해야 합니다. 아래 명령어를 사용하여 설치할 수 있습니다.

pip install workalendar

휴일 사이의 날짜 가져오기

workalendar는 여러 나라의 휴일 정보를 제공하고 있습니다. 예를 들어, 한국의 경우 SouthKorean 클래스를 사용할 수 있습니다. 아래는 한국의 휴일 사이의 모든 날짜를 가져오는 예제입니다.

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

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

all_dates = []
current_date = start_date

while current_date <= end_date:
    if not cal.is_working_day(current_date):
        all_dates.append(current_date)
    current_date += timedelta(days=1)
    
print(all_dates)

위 예제를 실행하면, 2022년 1월 1일부터 12월 31일까지의 한국의 휴일 사이의 모든 날짜를 출력합니다.

이전/다음 휴일 가져오기

특정 날짜의 이전 혹은 다음 휴일을 가져오려면 get_previous_holiday 혹은 get_next_holiday 메서드를 사용합니다.

from workalendar.asia import SouthKorean
from datetime import date

cal = SouthKorean()
target_date = date(2022, 1, 15)

previous_holiday = cal.get_previous_holiday(target_date)
next_holiday = cal.get_next_holiday(target_date)

print('이전 휴일:', previous_holiday[0])
print('다음 휴일:', next_holiday[0])

위 예제는 2022년 1월 15일의 이전 휴일과 다음 휴일을 출력합니다.

결론

workalendar 라이브러리를 사용하면 특정 날짜의 이전/다음 휴일 혹은 주말이 포함되는 휴일 사이의 모든 날짜를 쉽게 구할 수 있습니다. 이를 통해 프로젝트에서 다양한 날짜 계산과 관련된 작업을 효율적으로 수행할 수 있습니다.

참고 자료