[python] pytz를 사용하여 특정 시간대에서 반기간 최소 및 최대 비즈니스 시간 계산하기
지금까지 pytz를 사용해 특정 시간대에서 날짜 및 시간을 조작하는 방법을 알아보았습니다. 이번에는 pytz를 사용하여 특정 시간대에서 반기간의 최소 및 최대 비즈니스 시간을 계산하는 방법을 알아보겠습니다. 반기간은 주중의 비즈니스 시간을 의미합니다.
필요한 라이브러리 가져오기
import pytz
from datetime import datetime, timedelta
특정 시간대 설정하기
tz = pytz.timezone('Asia/Seoul')
반기간의 최소 및 최대 비즈니스 시간 계산하기
now = datetime.now(tz)
# 현재 시간에서 가장 가까운 이전 비즈니스 시간 계산
last_business_time = tz.normalize(now - timedelta(days=1))
while last_business_time.weekday() >= 5: # 주말인 경우
last_business_time = tz.normalize(last_business_time - timedelta(days=1))
# 현재 시간에서 가장 가까운 다음 비즈니스 시간 계산
next_business_time = tz.normalize(now + timedelta(days=1))
while next_business_time.weekday() >= 5: # 주말인 경우
next_business_time = tz.normalize(next_business_time + timedelta(days=1))
위의 코드에서는 현재 시간에서 가장 가까운 이전 비즈니스 시간과 다음 비즈니스 시간을 계산합니다. 이 때, 주말인 경우 비즈니스 시간을 계산하기 위해 weekday()
함수를 사용합니다.
결과 출력하기
print("마지막 비즈니스 시간:", last_business_time)
print("다음 비즈니스 시간:", next_business_time)
위의 코드를 실행하면 현재 시간을 기준으로 마지막 비즈니스 시간과 다음 비즈니스 시간이 출력됩니다.
결론
pytz를 사용하여 특정 시간대에서 반기간의 최소 및 최대 비즈니스 시간을 계산하는 방법에 대해 알아보았습니다. 이를 활용하면 다양한 시간 조작 및 비즈니스 로직에 유용하게 사용할 수 있습니다.
참고 자료
- pytz documentation: https://pypi.org/project/pytz/
- datetime module documentation: https://docs.python.org/3/library/datetime.html