Differences between Python datetime and result values according to date class changes

Asked 2 years ago, Updated 2 years ago, 91 views

It's a program that measures the time left until Christmas.

import datetime as dt
a=dt.datetime.today()
print(f) Today is {a.the month of the yearIt's day}.')
xmas=dt.date(2022,12,25)
su=xmas - dt.datetime.now()
print('Time Remaining',su.days,su.seconds//3600)

----------------------------------------------------------------------------------------
Today is June 12, 2022.
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_11004/4119043594.py in <module>
      3print(f'today is {a.the month of the yearIt's day}.')
      4 xmas=dt.date(2022,12,25)
----> 5 su=xmas - dt.datetime.now()
      6 print('Time Remaining',su.days,su.seconds//3600)

TypeError: unsupported operand type(s) for -: 'datetime.date' and 'datetime.datetime'

Didn't you get an error because you couldn't write - in datetime.date and datetime as a type error?

But if you write datetime.datetime in the code below, it will be executed, but I wonder why it's like this!

import datetime as dt
a=dt.datetime.today()
print(f) Today is {a.the month of the yearIt's day}.')
xmas=dt.datetime(2022,12,25)
su=xmas - dt.datetime.now()
print('Time Remaining',su.days,su.seconds//3600)
---------------------------------------------------------------------------------------
Today is June 12, 2022.
195 7
---------------------------------------------------------------------------------------

Thank you for your answer!

python datetime date

2022-09-20 08:55

1 Answers

>>> 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)


2022-09-20 08:55

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.