[python] pytz를 사용하여 특정 시간대에서 특정 날짜 범위의 연간 비즈니스 시간 계산하기

비즈니스 애플리케이션에서는 특정 시간대에서 비즈니스일 또는 비즈니스 시간을 계산해야 하는 경우가 많습니다. 이를 위해 pytz 라이브러리를 사용하여 특정 시간대에서 특정 날짜 범위의 연간 비즈니스 시간을 계산해볼 것입니다.

pytz 설치하기

pytz는 Python에서 시간대를 다룰 때 사용되는 라이브러리입니다. 다음 명령을 사용하여 pytz를 설치하세요.

pip install pytz

연간 비즈니스 시간 계산하기

다음은 pytz를 사용하여 특정 시간대에서 특정 날짜 범위의 연간 비즈니스 시간을 계산하는 예제 코드입니다.

import pytz
from datetime import datetime, timedelta

def calculate_business_hours(start_date, end_date, time_zone):
    business_hours = timedelta()
    current_date = start_date

    while current_date <= end_date:
        if current_date.weekday() < 5:  # 주중(월~금)인 경우에만 비즈니스 시간으로 계산
            start_time = datetime.combine(current_date, datetime.min.time())
            start_time = time_zone.localize(start_time)
            end_time = start_time + timedelta(hours=8)  # 비즈니스 시간은 8시간으로 가정
            end_time = end_time.astimezone(time_zone)
            business_hours += end_time - start_time

        current_date += timedelta(days=1)

    return business_hours

# 예제 실행
start_date = datetime(2022, 1, 1)
end_date = datetime(2022, 12, 31)
time_zone = pytz.timezone('Asia/Seoul')

result = calculate_business_hours(start_date, end_date, time_zone)
print(f"연간 비즈니스 시간: {result}")

위의 코드에서는 calculate_business_hours() 함수를 정의하여 시작 날짜(start_date), 종료 날짜(end_date), 시간대(time_zone)를 매개변수로 받습니다. 주중(월~금)인 경우에만 비즈니스 시간으로 계산하며, 비즈니스 시간은 8시간으로 가정합니다. 주어진 날짜 범위 내에서 주중의 비즈니스 시간을 계산하여 business_hours에 누적합니다. 계산된 비즈니스 시간은 함수의 반환값으로 반환됩니다.

위의 예제 코드를 실행하면 “연간 비즈니스 시간: XXXX”와 같은 결과가 출력될 것입니다.

참고 자료