且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用日期时间与 Django 中的日期进行比较

更新时间:2022-05-24 23:05:27

我觉得问题出在线路上

if datetime.now() == payment_date:

从字面上看,payment_date 是否是现在.我想你想看看现在是否大于或等于 payment_date,在这种情况下你应该使用

That will literally see if the payment_date is right now. I think you want to see if now is greater than or equal to the payment_date, in which case you should use

if datetime.now() >= payment_date:

您也可以在查询数据库时过滤发票:

You can also just filter the invoices when you query the database:

invoices_list = Invoice.objects.filter(payment_date__lte=datetime.now())

更新

你的代码是错误的,因为你有互斥的条件.看:

Update

Your code is wrong because you have mutually exclusive conditionals. Look:

if payment_date <= datetime.now():
    owing = invoice_gross
    if payment_date > datetime.now():
        owing = 0

首先检查 payment_date 是否在现在之前.然后它将owing 设置为invoice_gross.然后在相同的条件中,它会检查payment_date是否在现在之后.但那不可能!如果 payment_datebefore 现在,你才在这个代码块中!

That first checks to see if payment_date is before now. Then it sets owing to invoice_gross. Then, in the same conditional, it checks to see if payment_date is after now. But that can't be! You are only in this block of code if payment_date is before now!

我认为你有一个缩进错误,想要这个:

I think you have an indentation error, and want this instead:

if payment_date <= datetime.now():
    owing = invoice_gross
if payment_date > datetime.now():
    owing = 0

这当然是一样的:

if payment_date <= datetime.now():
    owing = invoice_gross
else:
    owing = 0