python/모듈

[Python] time - 시간

wjwkddyd221001 2022. 12. 8. 10:09

1. 현재시각 time.time()

import time

t = time.time()
# 1970년 1월 1일 0시 0분 0초 이후로 경과한 시간을 초 단위로 반환
print(t) 
print(type(t)) # type: float

 

2. time 객체 time.localtime()

import time

# 입력값 없으면 현재 시간이 기본값 
print(time.localtime())

# time.struct_time(tm_year=2022, tm_mon=12, tm_mday=8, tm_hour=9, tm_min=54, tm_sec=24, tm_wday=3, tm_yday=342, tm_isdst=0)
print(time.localtime(time.time()))

# <class 'time.struct_time'>
print(type(a))

 

3. 출력 포맷 지정 time.strftime()

time 객체가 주어질 때, 지정한 format으로 만들어 string값을 반환한다.

now = time.localtime()

t = time.strftime("%Y-%m-%d", now)
print(t) # 2022-12-08
print(type(t)) # <class 'str'>


t2 = time.strftime("%Y-%m-%d %H:%M:%S", now)
print(t2) # 2022-12-08 10:06:39

자세한 출력 포맷은 다음을 참고하자

https://docs.python.org/ko/3/library/time.html#time.strftime

 

참고자료

https://greeksharifa.github.io/references/2021/05/18/time-datetime-usage/