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

비즈니스 시간을 기준으로 특정 날짜 범위 내에서 통계를 계산하는 경우, 시간대를 고려해야 합니다. 이를 위해 Python에서 pytz 라이브러리를 사용할 수 있습니다. pytz는 시간대 관련 작업을 쉽게 처리할 수 있는 강력한 도구입니다.

설치

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

pip install pytz

예제 코드

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

import pytz
from datetime import datetime, timedelta

# 특정 날짜 범위 설정
start_date = datetime(2022, 1, 1)
end_date = datetime(2022, 1, 31)

# 시간대 설정
timezone = pytz.timezone('Asia/Seoul')

# 비즈니스 시간으로 필터링하기 위한 시작 및 종료 시간 설정
business_start_time = datetime.strptime('09:00', '%H:%M').time()
business_end_time = datetime.strptime('18:00', '%H:%M').time()

# 통계 계산을 위한 변수 초기화
total_hours = 0
business_hours = 0

# 특정 날짜 범위에서 비즈니스 시간에 대한 통계 계산
current_date = start_date
while current_date <= end_date:
    current_date = timezone.localize(current_date)
    
    if business_start_time <= current_date.time() <= business_end_time:
        business_hours += 1
    total_hours += 1
    
    current_date += timedelta(days=1)

# 통계 결과 출력
print(f"Total hours: {total_hours}")
print(f"Business hours: {business_hours}")
print(f"Non-business hours: {total_hours - business_hours}")

위의 코드에서는 datetime 모듈을 사용하여 날짜 범위를 설정하고, pytz를 사용하여 시간대를 설정합니다. 그 후, 비즈니스 시간의 시작 시간과 종료 시간을 설정합니다. 특정 날짜 범위 내의 시간을 비즈니스 시간으로 필터링하여 통계를 계산하고 결과를 출력합니다.

이 예제는 한국(Asia/Seoul) 시간대를 기준으로 비즈니스 시간을 계산합니다. 필요에 따라 시간대를 변경하거나 비즈니스 시간의 시작 및 종료 시간을 수정하여 사용할 수 있습니다.

참조