파이썬에서 자주 사용되는 시간 관련 모듈인 datetime과 time에 대해 알아보겠습니다.
시간 관련 모듈
목차
1. datetime 모듈
1) datetime 구성
import datetime
# 오늘 날짜 만들기
today = datetime.datetime.now() # 현재 시간 기록
# datetime 구성요소
print(today)
print(today.year) # 연도
print(today.month) # 월
print(today.day) # 일
print(today.hour) # 시
print(today.minute) # 분
print(today.second) # 초
print(today.microsecond) # 마이크로초
# datetime 형태 바꾸기
today_timestamp = today.timestamp() #현재 시간을 Unix time(1970년 1월 1일 0시 0분 0초로부터 현재까지 누적된 초)로 변환
print(today_timestamp)
# datetime 연산
one_day = datetime.timedelta(days = 1) # timedelta를 생성해 더하거나 뺄 수 있음
print(today+one_day)
pi_day = datetime.datetime(2024, 3, 14, 13, 6, 15)
diff = today - pi_day
print(diff) # timedelta를 쓰지 않고 바로 빼기 가능
print(diff.seconds) # 오늘과 pi_day의 차이를 누적된 초(second)로 표현
print(diff.days) # 오늘과 pi_day의 차이를 누적된 일(day)로 표현
print(diff.microseconds)
pi_day_timestamp = pi_day.timestamp()
print(today_timestamp)
print(pi_day_timestamp)
print(today_timestamp - pi_day_timestamp) #timestamp도 연산이 가능함
# datetime 포매팅: datetime을 strftime() 함수로 표현되는 문자열로 변환
today_str = today.strftime("%A, %B %dth %Y") # 자세한 내용은 본문 참고
print(today_str)
2024-07-30 22:54:09.135257
2024
7
30
22
54
9
135257
1722347649.135257
2024-07-31 22:54:09.135257
138 days, 9:47:54.135257
35274
138
135257
1722347649.135257
1710389175.0
11958474.135257006
Tuesday, July 30th 2024
2) datetime 포매팅
strftime() 함수를 통해 datetime을 문자열로 포매팅할 수 있다.
포맷 코드 | 설명 | 예시 |
%a | 요일(짧은 버전) | Mon |
%A | 요일(풀 버전) | Monday |
%w | 요일(숫자 버전, 0~6, 0이 일요일) | 1 |
%d | 일(1~31) | 18 |
%b | 월(짧은 버전) | Nov |
%B | 월(풀 버전) | November |
%m | 월(숫자 버전, 01~12) | 11 |
%y | 연도(짧은 버전) | 16 |
%Y | 연도(풀 버전) | 2016 |
%H | 시간(00~23) | 14 |
%I | 시간(00~12) | 02 |
%p | AM / PM | PM |
%M | 분(00~59) | 08 |
%S | 초(00~59) | 49 |
%f | 마이크로초(000000~999999) | 768812 |
%Z | 표준시간대 | PST |
%j | 1년 중 며칠째인지(001~366) | 162 |
%U | 1년 중 몇주째인지(00~53, 일요일이 시작점) | 35 |
%W | 1년 중 몇주째인지(00~53, 월요일이 시작점) | 50 |
2. time 모듈
1) time 구성
시간을 표시할 뿐만 아니라 딜레이도 가능하다. 이 기능 외에도 여러 함수를 적용할 수 있다.
import time
# 현재 시간 표시
today = time.time() # 현재 시간을 초단위로 반환(UNIX time) == datetime 모듈에서 .timestamp()
print(today)
# 딜레이
for i in range(1,6):
print(i)
time.sleep(1) # 1초 지연 후 다음 for문 수행 -> 1 출력 후 1초 뒤에 2 출력 ... 5 출력 후 마무리
# time 형태 변환
local_today = time.localtime(today) # UNIX time 형태를 YYYY MM DD HH MM SS 형태로 변환
print(local_today)
# time 포매팅: localtime() 형식의 시간데이터를 문자열로 포매팅
today_str = time.strftime("%Y년 %m월 %d일 %H시 %M분 %S초", local_today) # %Y = 연도, %m = 월, %d = 일, %H = 시, %M = 분, %S = 초
print(today_str)
1722348728.9139957
1
2 # 1 출력 후 1초가 지나서 2 출력
3
4
5
time.struct_time(tm_year=2024, tm_mon=7, tm_mday=30, tm_hour=23, tm_min=12, tm_sec=8, tm_wday=1, tm_yday=212, tm_isdst=0)
2024년 07월 30일 23시 12분 08초
3. datetime 모듈과 time 모듈 활용
내용 입력.
'코드잇 스프린트 > 파이썬' 카테고리의 다른 글
절대경로 vs. 상대경로 (0) | 2024.07.31 |
---|---|
클래스 변수와 클래스 메소드 (0) | 2024.07.30 |
정적 메소드 (0) | 2024.07.25 |
클래스와 인스턴스 (0) | 2024.07.25 |
pass, continue, 그리고 break (0) | 2024.07.19 |