[python] 파이썬 workalendar를 사용하여 특정 날짜의 이전/다음 휴일에서 가장 가까운 영업일 날짜 가져오기
어떤 날짜가 휴일인지를 확인하고, 해당 날짜가 영업일일 경우에는 그대로 반환하고, 휴일일 경우에는 가장 가까운 영업일 날짜를 반환하는 기능을 구현해야 할 때가 있습니다. 이런 경우에는 파이썬의 workalendar
라이브러리를 사용하여 간편하게 처리할 수 있습니다.
workalendar 설치
pip install workalendar
코드 예시
from workalendar.asia import SouthKorea
from datetime import date, timedelta
def find_nearest_business_day(target_date):
cal = SouthKorea()
nearest_business_day = target_date
while not cal.is_working_day(nearest_business_day):
nearest_business_day += timedelta(days=1)
return nearest_business_day
target_date = date(2022, 1, 1)
nearest_business_day = find_nearest_business_day(target_date)
print(nearest_business_day) # 2022-01-03
코드 설명
workalendar
라이브러리에서SouthKorea
클래스를 가져옵니다.- 가져온 클래스를 이용하여 특정 날짜가 영업일인지 확인하는 함수
is_working_day
를 사용합니다. target_date
의 값을 지정하여 가장 가까운 영업일을 찾기 위해nearest_business_day
변수에target_date
값을 할당합니다.nearest_business_day
가 영업일이 아닐 경우에는+1
을 하여 다음 날짜를 확인합니다.- 영업일이 되는 순간의
nearest_business_day
값을 반환합니다.
위의 예시 코드에서는 2022년 1월 1일
을 대상으로 가장 가까운 영업일을 찾아 출력하고 있습니다.