我想找到两天之间有多少天。下一步是找出两天之间有多少小时,但这是以后的事情。我用今天的日期创建了一个日期对象,并用用户输入创建了另一个日期对象,然后从较大的日期中减去较小的日期。我认为这是我要出问题的地方,因为当两个日期都都很幼稚时,从另一个日期中减去一个日期是没有意义的,但是从另一个日期时间(知道)中减去一个日期时间是有意义的吗?
我已经使用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)
```
答案 0 :(得分:0)
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)