Using datetime to compare with dates in Django

后端 未结 2 1194
暖寄归人
暖寄归人 2021-02-04 12:53

I have a question in Django on how you can compare dates to solve some solutions. For example I have a datefield in my models.py Like below.

class Invoice(models         


        
2条回答
  •  心在旅途
    2021-02-04 13:27

    I think the problem is in the line

    if datetime.now() == 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
    

    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
    

    Which, of course, is the same as:

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

提交回复
热议问题