파이썬 현재 날짜 시간

우리는 Python datetime 모듈을 사용하여 로컬 시스템의 현재 날짜와 시간을 가져올 수 있습니다.

from datetime import datetime

# 로컬 시스템의 현재 날짜와 시간
print(datetime.now())

출력: 2018-09-12 14:17:56.456080

Python 현재 날짜

로컬 시스템의 날짜만 관심이 있다면 datetime date() 메서드를 사용할 수 있습니다.

print(datetime.date(datetime.now()))

출력: 2018-09-12

Python 현재 시간

로컬 시스템에서 시간만 원한다면 datetime 객체를 인수로 전달하여 time() 메서드를 사용하세요.

print(datetime.time(datetime.now()))

출력: 14:19:46.423440

Python 시간대별 현재 날짜 및 시간 – pytz

대부분의 경우에는 날짜를 특정한 시간대로 원합니다. 그렇게 하면 다른 사람들도 사용할 수 있습니다. Python datetime now() 함수는 tzinfo 추상 기본 클래스의 구현이어야 하는 시간대 인자를 허용합니다. Python pytz는 시간대 구현을 얻는 데 사용할 수 있는 인기 있는 모듈 중 하나입니다. 다음 PIP 명령을 사용하여 이 모듈을 설치할 수 있습니다.

pip install pytz

pytz 모듈을 사용하여 특정 시간대의 시간을 가져오는 몇 가지 예제를 살펴보겠습니다.

import pytz

utc = pytz.utc
pst = pytz.timezone('America/Los_Angeles')
ist = pytz.timezone('Asia/Calcutta')

print('Current Date Time in UTC =', datetime.now(tz=utc))
print('Current Date Time in PST =', datetime.now(pst))
print('Current Date Time in IST =', datetime.now(ist))

결과:

Current Date Time in UTC = 2018-09-12 08:57:18.110068+00:00
Current Date Time in PST = 2018-09-12 01:57:18.110106-07:00
Current Date Time in IST = 2018-09-12 14:27:18.110139+05:30

지원되는 모든 시간대 문자열을 알고 싶다면 다음 명령을 사용하여 이 정보를 출력할 수 있습니다.

print(pytz.all_timezones)

이 명령은 pytz 모듈에 의해 지원되는 모든 시간대 목록을 출력합니다.

Python Pendulum 모듈

Python Pendulum 모듈은 또 다른 시간대 라이브러리이며, 그 문서에 따르면 pytz 모듈보다 빠릅니다. 아래 PIP 명령을 사용하여 Pendulum 모듈을 설치할 수 있습니다.

pip install pendulum

pendulum.timezones 속성에서 지원되는 시간대 문자열 목록을 가져올 수 있습니다. Pendulum 모듈을 사용하여 다른 시간대에서 현재 날짜와 시간 정보를 가져오는 몇 가지 예제를 살펴보겠습니다.

import pendulum

utc = pendulum.timezone('UTC')
pst = pendulum.timezone('America/Los_Angeles')
ist = pendulum.timezone('Asia/Calcutta')

print('Current Date Time in UTC =', datetime.now(utc))
print('Current Date Time in PST =', datetime.now(pst))
print('Current Date Time in IST =', datetime.now(ist))

결과:

Current Date Time in UTC = 2018-09-12 09:07:20.267774+00:00
Current Date Time in PST = 2018-09-12 02:07:20.267806-07:00
Current Date Time in IST = 2018-09-12 14:37:20.267858+05:30

당신은 우리의 GitHub 저장소에서 완전한 Python 스크립트와 더 많은 Python 예제를 확인할 수 있습니다.

Source:
https://www.digitalocean.com/community/tutorials/python-current-date-time