파이썬에서 현재 시간을 얻는 방법

Jinku Hu 2023년1월30일 Python Python DateTime
  1. 파이썬에서 현재 시간을 얻는 datetime 모듈
  2. 파이썬에서 현재 시간을 얻는 time 모듈
파이썬에서 현재 시간을 얻는 방법

파이썬에서 현재 시간, 즉 날짜 시간과 시간을 얻기 위해 두 개의 모듈을 사용할 수 있습니다.

파이썬에서 현재 시간을 얻는 datetime 모듈

>>> from datetime import datetime
>>> datetime.now()
datetime.datetime(2018, 7, 17, 22, 48, 16, 222169)

연도, 월, 일 및 시간을 포함한 날짜 시간 정보가 포함 된 datetime 객체를 반환합니다.

string 형식을 선호한다면 strftime 메소드를 사용하여 datetime 오브젝트 인스턴스를 인수에 정의 된 문자열 형식으로 변환 할 수 있습니다.

>>> datetime.now().strftime('%Y-%m-%d %H:%M:%S')
'2018-07-17 22:54:25'

다음은 strftime 형식 문자열의 지시문 스 니펫입니다.

지령 의미
%d 월의 일을 10 진수로 표시 [01,31].
%H 십진수로 표현 된 시간 (24 시간제) [00,23].
%m 십진수로 된 월 [01,12].
%M 십진수로 된 분 [00,59].
%S 두 번째는 10 진수입니다 [00,61].
%Y 십진수로 세기를 가진 년.

날짜가없는 현재 시간 만

>>> from datetime import datetime
>>> datetime.now().time()
datetime.time(23, 4, 0, 13713)

파이썬에서 현재 시간을 얻는 time 모듈

파이썬에서 현재 시간을 가져 오기위한 time.strftime

import time

time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
"2018-07-17 21:06:40"
주의
이름에서 알 수 있듯이 time.localtime()은 표준 시간대의 현지 시간을 반환합니다. UTC 시간이 선호된다면 time.gmtime()이 올바른 선택입니다.

파이썬에서 현재 시간을 가져 오기위한 time.ctime

import time

time.ctime()
"Tue Oct 29 11:21:51 2019"

결과적으로 ctime 은 GUI 에 표시하거나 콘솔에 인쇄하기에 더 친숙합니다. 요일, 월, 일, 시간 및 연도를 얻기 위해 분할 될 수도 있습니다.

>>> import time
>>> A = time.ctime()
>>> A = A.split()
>>> A
['Tue', 'Oct', '29', '12:38:44', '2019']
주의
time.ctime()은 운영 체제에 따라 다릅니다. 즉, OS 가 다르면 변경 될 수 있습니다. 다른 운영 체제에서 표준이 될 것으로 기대하지 마십시오.
이 방법은 기록 유지에 좋지 않습니다.
튜토리얼이 마음에 드시나요? DelftStack을 구독하세요 YouTube에서 저희가 더 많은 고품질 비디오 가이드를 제작할 수 있도록 지원해주세요. 구독하다
작가: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn Facebook

관련 문장 - Python DateTime