Python 如何从另一个对象中减去一个日期对象

How to subtract a date object from another in Python

我想知道两天之间有多少天。下一步是找出两天之间有多少小时,但那是以后的事。我用今天的日期创建了一个日期对象,用用户输入创建了另一个日期对象,然后从较大的日期中减去较小的日期。我认为这就是我要出错的地方,因为从另一个日期中减去一个日期是没有意义的,当两个日期都是天真的时候,但是从另一个日期时间中减去一个日期时间是有意义的(知道)?

我已经使用 print(type(var)) 验证了对象的类型。创建的两个对象都是date类型,相减的结果是一个timedelta对象,符合预期。减去日期对象给我错误的天数(400 左右),而在我的情况下它应该是 350。

from datetime import date, timedelta, datetime
days = list(range(1, 32))
months = list(range(1, 13))
today = date.today()

def inputInteger(message):
    while True:
        try:
            userInput = int(input(message))
        except ValueError:
            print("Please enter an integer.")
            continue
        else:
            return userInput
            break


def inputMonth(message):
    while True:
        message = inputInteger(message)
        if message in months:
            return message
            break
        else:
            print("Please pick a value from 1-12")


def inputDay(message):
    while True:
        message = inputInteger(message)
        if int(message) in days:
            return message
            break
        else:
            print("Please pick a value from 1-31")


year = int(inputInteger('Enter a year'))
month = int(inputMonth('Enter a month (1-12)'))
day = int(inputDay('Enter a day (1-31)'))
# 2. add exception handling: leap years, leap seconds?, etc.
significantDate = date(year, month, day)
print("significant date:", significantDate, "of type", type(significantDate))
print("today:", today, "of type", type(today))
# 2. Tell me how many days are left until a certain date
if today > significantDate:
    delta = today - significantDate
    print("Days left:", delta.days)
else:
    print("entered less than")
    delta = significantDate - today
    print("Days left:", delta.days) 
    ```


from datetime import datetime

year = int(inputInteger('Enter a year'))
month = int(inputMonth('Enter a month (1-12)'))
day = int(inputDay('Enter a day (1-31)'))

significantDate =datetime.strptime(str(year) +str(month) + str(day), '%Y%m%d') 


today = datetime.now()
print(today)



dt = today - significantDate

print(dt.days)