datetime은 현재시간을 구하거나 시간간의 간격을 구하는 등의 시간에 관련된 것들을 제공하는 모듈입니다. 매우 사용하기 쉬운 모듈이긴 하지만 그만큼 많이 사용하기도 하는 모듈이기에 정리해 둡니다. 다음과 같이 import를 하고 사용하면 됩니다. datetime 모듈에는 datetime이라는 동일한 이름의 클래스가 존재하기 때문에 그냥 import 하면 datetime.datetime이라는 이상한 이름이 되어 버려 저는 다음과 같이 모듈 이름을 바꿔서 사용하는 편입니다.
import datetime as dt
다른 클래스도 있지만 여기서 다룰 클래스는 총 4가지 입니다. 간단하게 표로 정리해 보겠습니다.
클래스명 | 설명 |
date | 날짜를 다룹니다 |
datetime | 날짜와 시간을 다룹니다. |
time | 시간만을 다룹니다 (00:00:00 ~ 23:59:59.xxx) |
timedelta | 시간 사이의 간격을 다룹니다. |
1. date
date는 날짜를 다루는 클래스입니다. 날짜는 년, 월, 일로 구성되며 다음과 같이 초기화 하여 사용하시면 됩니다. today() 함수를 통해 현재 날짜를 얻을 수도 있습니다.
# 현재 날짜 구하기
current_date = dt.date.today()
# 특정 날짜로 지정하기
special_date = dt.date(2000, 1, 1)
print(current_date)
print(special_date)
# 출력
2024-02-06
2000-01-01
임의의 텍스트 형태로 날짜를 출력하고 싶다면 srttime 함수를 사용하시면 됩니다. 다음과 같이 사용하여도 위와 유사한 형태로 출력할 수 있습니다.
print(current_date.strftime('%Y-%m-%d'))
# 출력
2024-02-06
2. datetime
datetime은 날짜와 시간을 같이 다룹니다. 마찬가지로 now() 함수를 통해 현재 날짜와 시간을 얻을 수 있습니다. 초기화시 년, 월, 일, 시간, 분, 초, 마이크로초 단위로 생성자 인자로 넣으며, 년, 월, 일 이하는 생략이 가능합니다. (0시 0분 0초로 세팅됨)
# 현재 날짜시간 구하기
current_datetime = dt.datetime.now()
# 특정 날짜시간으로 지정하기
special_datetime = dt.datetime(2000, 1, 1)
# 아래 두 줄은 비슷한 결과를 출력합니다.
print(current_datetime)
print(special_datetime)
# 출력
2024-02-06 11:49:48.564635
2000-01-01 00:00:00
date와 마찬가지로 임의의 텍스트 형태로 날짜를 출력하고 싶다면 srttime 함수를 사용하시면 됩니다. 다음과 같이 사용하여도 위와 유사한 형태로 출력할 수 있습니다.
print(current_datetime.strftime('%Y-%m-%d %H:%M:%S.%f'))
# 출력
2024-02-06 11:49:48.564635
3. time
time은 시간을 다룹니다. time 함수는now() 함수를 제공하고 있지 않습니다. 현재 시간으로 세팅하고 싶다면 datetime을 얻고 time() 함수를 통해 구할 수 있습니다. 초기화시 시간, 분, 초, 마이크로초 단위로 생성자 인자로 넣으며 생략이 가능합니다. (생략된 부분은 0으로 세팅됨) fromisoformat 함수 (ISO 8601 표준)를 통해 문자열로 시간을 설정할 수도 있습니다.
##
# 현재 시간 구하기
current_time = dt.datetime.today().time()
# 특정 시간으로 지정하기
special_time1 = dt.time(12, 34, 56)
special_time2 = dt.time.fromisoformat('12:34:56')
print(current_time)
print(special_time1)
print(special_time2)
# 출력
11:49:48.564635
12:34:56
12:34:56
date나 time과 마찬가지로 임의의 텍스트 형태로 날짜를 출력하고 싶다면 srttime 함수를 사용하시면 됩니다. 물론 직접 변수에 접근해 얻으셔도 마찬가지겠죠. 다음과 같이 유사한 형태로 출력할 수 있습니다.
print(current_time.strftime('%H:%M:%S.%f'))
text = str.format('{0:02d}', current_time.hour) + ":"
text += str.format('{0:02d}', current_time.minute) + ":"
text += str.format('{0:02d}', current_time.second) + "."
text += str.format('{0:06d}', current_time.microsecond)
print(text)
# 출력
11:49:48.564635
11:49:48.564635
4. timedelta
마지막으로 timedelta에 대해 알아보겠습니다. timedelta는 시간과 시간 사이의 간격을 구할 때 주로 사용됩니다. 다음 표와 같이 클래스간의 연산 (+, -) 수행시 결과로 얻을 수 있습니다. 클래스간에 연산이 불가능한 경우도 있음을 주의하세요.
class1 | class2 | 출력 class |
date | date | timedeleta |
datetime | datetime | timedeleta |
datetime | date | X (불가능) |
date | time | X (불가능) |
time | time | X (불가능) |
datetime | timedelta | datetime |
date | timedelta | date |
다음과 같이 시간 간격을 출력할 수 있습니다. 내부적으로 시간은 days + seconds + microseconds로 관리되며 이를 이용해 출력을 해도 비슷한 결과를 얻을 수 있습니다.
# 시간 차이 계산하기
diff_time1:dt.timedelta = current_date - special_date
diff_time2:dt.timedelta = current_datetime - special_datetime
#diff_time3 = current_datetime - current_date # datetime과 date는 뺄셈이 안됩니다.
#diff_time4 = current_time - special_time1 # time끼리는 뺄셈이 안됩니다.
#diff_time5 = current_date - special_time1 # date과 time은 뺄셈이 안됩니다
#diff_time6 = current_datetime - special_time1 # datetime과 time은 뺄셈이 안됩니다
print(diff_time1) # current_date는 0시 0분 0초로 계산되어 days만 값을 가집니다.
print(diff_time2)
diff_text = str(diff_time2.days) + " days, "
diff_text += str.format('{0:02d}', int(diff_time2.seconds / 3600)) + ":"
diff_text += str.format('{0:02d}', int((diff_time2.seconds % 3600) / 60)) + ":"
diff_text += str.format('{0:02d}', int(diff_time2.seconds % 60)) + "."
diff_text += str.format('{0:06d}', diff_time2.microseconds)
print(diff_text)
# 출력
8802 days, 0:00:00
8802 days, 12:16:17.119787
8802 days, 12:16:17.119787
마지막으로 datetime + timedelta 와 date + timedelta의 예제만 보이고 마치도록 하겠습니다. timedelta는 time에서 값을 얻어서 이를 사용하였고 date + timedelta는 날짜만 사용되기에 timedelta내의 days만 사용되고 나머지 시간은 무시됩니다.
time1 = dt.timedelta(
hours=special_time1.hour,
minutes=special_time1.minute,
seconds=special_time1.second,
microseconds=special_time1.microsecond)
time2:dt.datetime = current_datetime - time1
print("'{0}' - '{1}' = '{2}'".format(current_datetime, time1, time2))
time3 = dt.timedelta(days=1, hours=23)
time4 = current_date + dt.timedelta(days=1, hours=23)
print("'{0}' + '{1}' = '{2}'".format(current_date, time3, time4))
#출력
'2024-02-06 12:28:50.827666' - '23:34:56' = '2024-02-05 12:53:54.827666'
'2024-02-06' + '1 day, 23:00:00' = '2024-02-07'
'Python' 카테고리의 다른 글
[Python] django (2/3) template 맛보기 (0) | 2024.05.25 |
---|---|
[Python] django (1/3) module 맛보기 (0) | 2024.04.13 |
[Python] Argument Parser (0) | 2024.02.02 |
[Python] wxPython 맛보기 (0) | 2023.12.14 |
[Python] Config Parser (0) | 2023.12.11 |