파이썬 datetime 과 date 클래스 변경에 따른 결과값의 차이
조회수 376회
크리스마스까지 남은 시간을 재는 프로그램입니다.
import datetime as dt
a=dt.datetime.today()
print(f'오늘은 {a.year}년 {a.month}월 {a.day}일 입니다.')
xmas=dt.date(2022,12,25)
su=xmas - dt.datetime.now()
print('남은 시간 ',su.days,su.seconds//3600)
----------------------------------------------------------------------------------------
오늘은 2022년 6월 12일 입니다.
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_11004/4119043594.py in <module>
3 print(f'오늘은 {a.year}년 {a.month}월 {a.day}일 입니다.')
4 xmas=dt.date(2022,12,25)
----> 5 su=xmas - dt.datetime.now()
6 print('남은 시간 ',su.days,su.seconds//3600)
TypeError: unsupported operand type(s) for -: 'datetime.date' and 'datetime.datetime'
이렇게 타입 에러로 datetime.date 와 datetime.datetime에선 - 를 못 쓴다고 오류가 뜬 것 아닌가요?
근데 밑에 코드에서 datetime.datetime을 쓰면 실행되는데 왜 이런지 궁금합니다!
import datetime as dt
a=dt.datetime.today()
print(f'오늘은 {a.year}년 {a.month}월 {a.day}일 입니다.')
xmas=dt.datetime(2022,12,25)
su=xmas - dt.datetime.now()
print('남은 시간 ',su.days,su.seconds//3600)
---------------------------------------------------------------------------------------
오늘은 2022년 6월 12일 입니다.
195 7
---------------------------------------------------------------------------------------
답변 감사합니다!
1 답변
-
>>> import datetime >>> datetime.date.today() datetime.date(2022, 6, 12) >>> d1 = datetime.date.today() >>> d2 = datetime.datetime.today() >>> d1 datetime.date(2022, 6, 12) >>> d2 datetime.datetime(2022, 6, 12, 20, 44, 11, 107192) >>> type(d1) <class 'datetime.date'> >>> now = datetime.datetime.now() >>> d1-now Traceback (most recent call last): File "<pyshell#8>", line 1, in <module> d1-now TypeError: unsupported operand type(s) for -: 'datetime.date' and 'datetime.datetime' >>> d2-now datetime.timedelta(days=-1, seconds=86377, microseconds=707055)
댓글 입력