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

파이썬에서 일반적으로 날짜와 시간을 다룰 때 datetime 모듈을 사용합니다. 그러나 국제적인 시간대를 다룰 때 pytz라이브러리를 사용해야 합니다. pytz는 세계 각지의 시간대 정보를 제공하며, 날짜와 시간에 대한 계산을 할 때 유용합니다.

이 글에서는 pytz를 사용하여 특정 시간대에서 특정 날짜 범위의 주간 비즈니스 시간을 계산하는 방법을 살펴보겠습니다.

먼저, pytz 모듈을 설치해야 합니다. 아래 명령을 사용하여 설치할 수 있습니다:

pip install pytz

이제 다음의 예제 코드를 통해 주간 비즈니스 시간을 계산하는 방법을 알아보도록 하겠습니다.

import pytz
from datetime import datetime, timedelta

# 필요한 시간대를 선택합니다.
timezone = pytz.timezone("Asia/Seoul")

# 비즈니스 시간 범위를 정의합니다.
start_date = datetime(2022, 1, 1)
end_date = datetime(2022, 12, 31)

# 비즈니스 시간을 계산하기 위한 변수를 초기화합니다.
total_business_hours = timedelta()

# 주간 비즈니스 시간을 계산합니다.
current_date = start_date
while current_date <= end_date:
    # 현재 날짜의 시작 시간과 종료 시간을 계산합니다.
    start_time = timezone.localize(datetime(current_date.year, current_date.month, current_date.day, 9, 0, 0))
    end_time = timezone.localize(datetime(current_date.year, current_date.month, current_date.day, 18, 0, 0))
    
    # 주말인 경우 비즈니스 시간을 계산하지 않습니다.
    if current_date.weekday() < 5:
        business_hours = end_time - start_time
        total_business_hours += business_hours
    
    # 다음 날짜로 이동합니다.
    current_date += timedelta(days=1)

# 결과 출력
print(f"Total business hours: {total_business_hours}")

이 예제 코드는 한국 표준시(Asia/Seoul)를 기준으로 주간 비즈니스 시간을 계산합니다. 비즈니스 시간은 주말(토요일과 일요일)을 제외하고, 매일 오전 9시부터 오후 6시까지로 정의되었습니다. 시작 날짜와 종료 날짜를 지정하여 원하는 날짜 범위의 비즈니스 시간을 계산할 수 있습니다.

pytz를 사용하면 세계 각지의 다양한 시간대를 다룰 수 있으며, 비즈니스 시간을 계산하는 등 다양한 시간 연산을 수행할 수 있습니다.

참고 자료: