首页 > 解决方案 > 如何正确使用 time.delta?

问题描述

我的代码有一些问题。我正在尝试在日期之间进行减法,但出现错误。我想用整数天或月来获得两个日期之间的差异。但是,即使我知道天数之间的差异,我也会得到这个输出:99 天,0:00:00,我不想得到时间声明。除此之外,当我进行比较以获得剩余月份时,我得到这个:TypeError:'<'在'datetime.timedelta'和'int'的实例之间不支持。如何将我的 r_days 作为剩余天数转换为整数,以及如何获得剩余月份的结果?

from datetime import datetime

date_format = "%d/%m/%Y"

exam_date = input('Exam Date: ')
exam_date = datetime.strptime(exam_date,date_format)


if exam_date < (datetime.strptime("05/07/2020", date_format)):
    print('Exam finished')
 
elif exam_date > (datetime.strptime("05/07/2020", date_format)):
    r_day = exam_date - (datetime.strptime("05/07/2020", date_format))
    
    if r_day<30:
    
        print(r_day,"days until the exam")
    else:
        r_months = r_day//30
        print(r_months, "months untill the exam")

标签: pythonpython-3.x

解决方案


不要使用原始的 timedelta 对象,而是使用它的days属性。而且您应该保存比较日期,而不是strptime一遍又一遍地使用:

from datetime import datetime

date_format = "%d/%m/%Y"

exam_date = input('Exam Date (DD/MM/YYYY): ')
exam_date = datetime.strptime(exam_date,date_format)

compare_date = datetime(2020, 7, 5)
if exam_date < compare_date:
    print('Exam finished')
 
elif exam_date > compare_date:
    r_day_diff = exam_date - compare_date
    
    if r_day_diff.days < 30:
        print(r_day_diff.days,"days until the exam")
    else:
        r_months = r_day_diff.days // 30
        print(r_months, "months until the exam")

else:
  print("Exam is today!")

推荐阅读