웹사이트 검색

Python 현재 날짜 시간


Python datetime 모듈을 사용하여 로컬 시스템의 현재 날짜와 시간을 얻을 수 있습니다.

from datetime import datetime

# Current date time in local system
print(datetime.now())

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

파이썬 현재 날짜

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

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

출력: 2018-09-12

파이썬 현재 시간

로컬 시스템에서 시간만 원하는 경우 datetime 객체를 인수로 전달하여 time() 메서드를 사용합니다.

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

출력: 14:19:46.423440

시간대의 Python 현재 날짜 시간 - pytz

대부분의 경우 다른 사람도 사용할 수 있도록 특정 시간대의 날짜를 원합니다. Python datetime now() 함수는 tzinfo 추상 기본 클래스의 구현이어야 하는 시간대 인수를 허용합니다. 파이썬 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 모듈은 또 다른 시간대 라이브러리이며 설명서에 따르면 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 예제를 확인할 수 있습니다.