[python] pytz를 사용하여 특정 시간대에서 현재 시각을 가져오는 방법은 무엇인가요?
- 먼저,
pytz
모듈을 설치해야 합니다. 다음 명령어를 사용하여 설치할 수 있습니다:pip install pytz
datetime
및pytz
모듈을 가져옵니다:from datetime import datetime import pytz
- 원하는 시간대의
timezone
객체를 생성합니다.pytz
의timezone
클래스를 사용하여 생성할 수 있습니다. 예를 들어, ‘Asia/Seoul’ 시간대를 사용하려면 다음과 같이 입력합니다:timezone = pytz.timezone('Asia/Seoul')
- 현재 시간을
datetime
객체로 가져옵니다. 이때,now()
메서드를 사용하고tz
매개변수로 위에서 생성한timezone
객체를 전달합니다:current_time = datetime.now(tz=timezone)
- 원하는 형식으로 현재 시간을 표시할 수 있습니다. 예를 들어, ‘YYYY-MM-DD HH:MM:SS’ 형식으로 출력하려면
strftime()
메서드를 사용합니다:formatted_time = current_time.strftime('%Y-%m-%d %H:%M:%S') print(f"The current time in Seoul is {formatted_time}")
이렇게 하면
Asia/Seoul
시간대에서의 현재 시간을 가져와서 원하는 형식으로 표시할 수 있습니다.
더 자세한 내용은 pytz 공식 문서를 참조하시기 바랍니다.