[python] pytz를 사용하여 특정 시간대의 현재 시간을 구하는 방법은 무엇인가요?
- pytz 라이브러리 설치하기:
pip install pytz
- datetime 모듈과 pytz 모듈을 import하기:
from datetime import datetime import pytz
- 특정 시간대의 현재 시간 구하기:
# 원하는 시간대의 이름을 변수에 할당 timezone_name = 'Asia/Seoul' # pytz 모듈을 사용하여 시간대 객체를 생성 timezone = pytz.timezone(timezone_name) # datetime 모듈을 사용하여 현재 시간을 가져온 후 시간대를 설정 current_time = datetime.now(timezone) # 현재 시간 출력 print("현재 시간:", current_time)
위의 코드는 pytz를 사용하여 ‘Asia/Seoul’ 시간대의 현재 시간을 구하는 예제입니다. 시간대를 변경하려면 timezone_name
변수의 값을 원하는 시간대의 이름으로 변경하십시오.
프로그램을 실행하면 해당 시간대의 현재 시간이 출력됩니다.