简体   繁体   English

Python:日期比较未通过相等性测试

[英]Python: Date compare fails equality test

I'm a python beginner.我是python初学者。 Here is the code that I'm trying to run:这是我试图运行的代码:

matexp = input("What's the material expiration date (mm/dd/yy): ")
matexpir = datetime.strptime(matexp, "%m/%d/%y")

d1 = datetime.today()

d2 = timedelta(days=30)

d3 = d1 + d2

if matexpir == d3:
    matstat = "CAUTION"
elif matexpir <= d1:
    matstat = "EXPIRED"
else :
    matstat = "Null"

While testing this code, I can get it to print matstat or Status = 'EXPIRED' on a table, but when I try to get it to print 'CAUTION', it doesn't and goes straight to 'Null'.在测试此代码时,我可以让它在表上打印 matstat 或 Status = 'EXPIRED',但是当我尝试让它打印'CAUTION'时,它不会并直接进入'Null'。 Why is that?这是为什么? How may I fix it?我该如何解决? Please help.请帮忙。

Thank you.谢谢你。

In its current form, the test is comparing a date and a datetime , which will obviously never be equal.在目前的形式中,测试是比较datedatetime ,这显然永远不会相等。

To address this, the comparison should be like-for-like.为了解决这个问题,比较应该是同类的。 Compare dates , with the time factor removed.比较dates ,去掉时间因素。


The fix:修复:

Change this:改变这个:

matexpir = datetime.strptime(matexp, "%m/%d/%y")

to:至:

matexpir = datetime.strptime(matexp, "%m/%d/%y").date()

And change this:并改变这个:

d1 = datetime.today()

to:至:

d1 = datetime.today().date()    

Full solution:完整解决方案:

from datetime import datetime, timedelta

matexp = input("What's the material expiration date (mm/dd/yy): ")
matexpir = datetime.strptime(matexp, "%m/%d/%y").date()

d1 = datetime.today().date()
d2 = timedelta(days=30)
d3 = d1 + d2

if matexpir == d3:
    matstat = "CAUTION"
elif matexpir <= d1:
    matstat = "EXPIRED"
else:
    matstat = "Null"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM