如何用输入日期减去今天的日期?

时间:2014-11-11 14:41:53

标签: python datetime python-3.x

我目前的代码:

import datetime
from time import strptime
leapyear = 0

isValid = False
while not isValid:
     in_date = input(" Please in put a year in the format dd/mm/yyyy ")
     try:
         d = strptime(in_date, '%d/%m/%Y')
         isValid=True
     except:
         print ("This is not in the right format")

diff = d -datetime.date.today()
print(in_date)
print(d)
print(diff)

我无法相互减去两个日期,输入日期和今天的日期。它抛出TypeError: unsupported operand type(s) for -: 'time.struct_time' and 'datetime.date'例外。

任何想法为什么?

2 个答案:

答案 0 :(得分:0)

datetime模块对象仅支持与同一库中的其他对象进行减法。 time模块struct_time元组不是其中之一。

使用datetime.datetime.strptime() class method来解析日期:

 d = datetime.datetime.strptime(in_date, '%d/%m/%Y')

然后使用datetime.date() method从结果中提取 一个date对象:

diff = d.date() - datetime.date.today()

结果是datetime.timedelta instance

不要抓住所有例外情况;只捕获strptime()在传递与预期格式ValueError不匹配的字符串while True: in_date = input(" Please in put a year in the format dd/mm/yyyy ") try: d = datetime.datetime.strptime(in_date, '%d/%m/%Y').date() break except ValueError: print ("This is not in the right format") 时抛出的内容:

break

我在这里使用while来结束{{1}}循环而不是使用标志变量。

答案 1 :(得分:0)

import datetime
from datetime import strptime
currentdate=datetime.date.today()
date_str = input("enter date in format dd/mm/yyy") #inputed date is in string need to conver ot into date 
#format_str = '%d/%m/%Y' # The format
datetime_obj = datetime.datetime.strptime(date_str, '%d/%m/%Y') # convert inputed date into date 
diff= datetime_obj.date() - currentdate # take .date because we only need date not time 

print("Current date ==",currentdate)
print("entered date ==",datetime_obj.date()) 
print("remaining Days left  ===",diff)