[python] pytz를 사용하여 특정 시간대에서 특정 날짜 범위의 최소 비즈니스 시간 가져오기

일반적으로 비즈니스 시간은 9시부터 17시까지입니다. pytz 패키지를 사용하여 특정 시간대에서 특정 날짜 범위의 최소 비즈니스 시간을 가져올 수 있습니다. 이를 위해 datetime 및 pytz 모듈을 사용합니다.

1. 필요한 모듈 가져오기

import pytz
from datetime import datetime, timedelta

2. 비즈니스 시간을 계산하기

def get_business_hours(start_date, end_date, timezone='UTC'):
    tz = pytz.timezone(timezone)
    business_start_time = datetime.strptime("9:00", "%H:%M").time()
    business_end_time = datetime.strptime("17:00", "%H:%M").time()

    start_datetime = tz.localize(datetime.combine(start_date, business_start_time))
    end_datetime = tz.localize(datetime.combine(end_date, business_end_time))

    business_hours = []

    current_datetime = start_datetime
    while current_datetime <= end_datetime:
        if current_datetime.time() >= business_start_time and current_datetime.time() <= business_end_time:
            business_hours.append(current_datetime)
        current_datetime += timedelta(hours=1)

    return business_hours

위의 함수는 시작 날짜와 종료 날짜를 받아 해당 기간 동안 비즈니스 시간에 해당하는 시간들을 리스트로 반환합니다. 입력된 시간대에 대해 시작 시간과 종료 시간을 설정한 후, 시작 시간과 종료 시간을 포함하는 비즈니스 시간의 모든 시간들을 리스트에 추가합니다. 비즈니스 시간은 1시간 간격으로 계산됩니다.

3. 예시 사용법

start_date = datetime(2022, 1, 1).date()
end_date = datetime(2022, 1, 10).date()
timezone = 'Asia/Seoul'

business_hours = get_business_hours(start_date, end_date, timezone)

for hour in business_hours:
    print(hour)

위의 예시 코드는 2022년 1월 1일부터 2022년 1월 10일까지의 기간 동안, 서울 시간대에서의 비즈니스 시간들을 출력하는 코드입니다. 출력 결과는 시작 날짜부터 종료 날짜까지의 모든 비즈니스 시간들입니다.

이렇게 pytz를 사용하여 특정 시간대에서 특정 날짜 범위의 최소 비즈니스 시간을 가져올 수 있습니다.

참고 자료