[python] pytz를 사용하여 특정 날짜 범위의 반기간 최소 및 최대 비즈니스 시간 계산하기
파이썬의 pytz
라이브러리를 사용하면 특정 날짜 범위의 반기간 최소 및 최대 비즈니스 시간을 계산할 수 있습니다. 이때, 반기간은 비즈니스 영업 시간 안에서의 시간 범위를 의미합니다.
1. pytz
라이브러리 설치하기
먼저, pytz
라이브러리를 설치해야 합니다. 아래의 명령어를 사용하여 설치하세요.
pip install pytz
2. 코드 예시
다음은 pytz
를 사용하여 특정 날짜 범위의 반기간 최소 및 최대 비즈니스 시간을 계산하는 코드의 예시입니다.
from datetime import datetime
import pytz
def get_business_start_end_times(start_date, end_date):
# 비즈니스 오픈 시간과 클로즈 시간 설정
business_open_time = datetime.strptime("09:00:00", "%H:%M:%S").time()
business_close_time = datetime.strptime("17:00:00", "%H:%M:%S").time()
# 타임존 설정
tz = pytz.timezone('Asia/Seoul')
# 시작 날짜 및 시간 설정
start_dt = datetime.combine(start_date, business_open_time)
start_dt = tz.localize(start_dt)
# 종료 날짜 및 시간 설정
end_dt = datetime.combine(end_date, business_close_time)
end_dt = tz.localize(end_dt)
# 반기간 최소 및 최대 비즈니스 시간 계산
if start_dt.weekday() < 5: # 주중인 경우
start_dt = max(start_dt, tz.localize(datetime.combine(start_date, business_open_time)))
end_dt = min(end_dt, tz.localize(datetime.combine(end_date, business_close_time)))
else: # 주말인 경우 다음 주 월요일로 계산
next_monday = start_date + timedelta(days=(7 - start_dt.weekday()) % 7)
start_dt = tz.localize(datetime.combine(next_monday, business_open_time))
end_dt = tz.localize(datetime.combine(next_monday, business_close_time))
return start_dt, end_dt
# 특정 날짜 범위를 입력하여 반기간 최소 및 최대 비즈니스 시간 계산
start_date = datetime.strptime("2022-01-01", "%Y-%m-%d").date()
end_date = datetime.strptime("2022-01-07", "%Y-%m-%d").date()
business_start_time, business_end_time = get_business_start_end_times(start_date, end_date)
print("반기간 최소 비즈니스 시간:", business_start_time)
print("반기간 최대 비즈니스 시간:", business_end_time)
위의 코드는 get_business_start_end_times
함수를 통해 특정 날짜 범위의 반기간 최소 및 최대 비즈니스 시간을 계산하는 예시입니다. 시작 날짜와 종료 날짜를 인자로 받아 해당 날짜 범위의 비즈니스 시간을 반환합니다.