python - 如何正确使用 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")
解决方案
不要使用原始的 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!")
推荐阅读
- c++ - Does C++ compiler always creates a default constructor if the programmer has not provided one?
- firebase-realtime-database - How to get value of a path in Firebase Realtime Database security rules
- c++ - Protected access specifier is in accessible
- jenkins - Github's webhook is not able to connect to jenkins server
- python - 如何将主 DataFrame 的每一列转换为单独的 DataFrame?
- python - 在函数外使用函数中定义的变量
- performance - 从本地加载 JS 文件,而不是从 CDN
- javascript - 单击按钮后隐藏组件(登录)并显示其他组件
- assembly - 在 C64 汇编程序中保存和重用寄存器?
- c# - Unity Newtonsoft JSON Android Build MissingMethodException:找不到类型“System.ComponentModel.ReferenceConverter”的构造函数