[Fixed]-Using datetime to compare with dates in Django

15πŸ‘

βœ…

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
πŸ‘€mipadi

10πŸ‘

Use datetime.now() (notice the parens). Other than that, remember that the field will always be a datetime object. Also, (I guess that) you should check only the date of the datetime to match the current date (or else it will only match that specific second). For that you have to check if payment_date.date() == date.today() (where date is datetime.date)

This also means that you can filter like this: Invoice.objects.filter(payment_date__lte=datetime.now()).

__lte, __gte, __lt, __gt are used for <=, >=, < and >

πŸ‘€Gabi Purcaru

0πŸ‘

Thank to Mushahid Khan
https://stackoverflow.com/a/37596662/12575117

(Short Code)
You can use this one:

from django.utils.timezone import datetime
πŸ‘€princep

Leave a comment