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

pytz는 Python에서 시간대 관련 작업을 수행하기 위해 사용되는 유용한 라이브러리입니다. 이 기능을 활용하여 특정 시간대에서 특정 날짜 범위의 마지막 비즈니스 시간을 가져오는 방법을 살펴보겠습니다.

1. 필요한 패키지 가져오기

import pytz
from datetime import datetime, timedelta

먼저 pytz와 datetime 모듈을 가져와야 합니다.

2. 특정 시간대 변수 설정하기

tz = pytz.timezone('Asia/Seoul')

원하는 시간대를 선택하여 변수에 저장합니다. 여기서는 ‘Asia/Seoul’을 선택했습니다.

3. 범위 설정하기

start_date = datetime(2022, 1, 1)
end_date = datetime(2022, 1, 31)

범위로 사용할 시작 날짜와 끝 날짜를 datetime 객체로 설정합니다.

4. 마지막 비즈니스 시간 계산하기

# 시작 날짜부터 끝 날짜까지 반복하면서 마지막 비즈니스 시간을 계산합니다.
current_date = start_date
last_business_time = None

while current_date <= end_date:
    # 주말인지 확인합니다.
    if current_date.weekday() < 5:  # 월요일(0)부터 금요일(4)까지를 평일로 간주합니다.
        # 비즈니스 시간을 확인하고 업데이트합니다.
        current_business_time = tz.localize(datetime.combine(current_date, datetime.max.time()))
        if last_business_time is None or current_business_time > last_business_time:
            last_business_time = current_business_time
    current_date += timedelta(days=1)

주말이 아닌 경우에만 비즈니스 시간을 계산하고, 마지막 비즈니스 시간을 업데이트합니다.

5. 결과 확인하기

print(last_business_time)

마지막 비즈니스 시간을 출력합니다.

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