Home > database >  I want to compare two date in django views py
I want to compare two date in django views py

Time:06-17

I want to compare two date to return something. I have been trying this for a long time. So what I want is:

I have a variable called current_date = date.today, now I want to compare current_date with anther datefield variable. I tried this code :

current_date = date.today()
# I am getting this another date from a html input type date
another_date = request.POST.get("date")
if current_date > another_date:
return True
else:
return False

But I am getting an error

'<' not supported between instances of 'datetime.date' and 'str'

How can solve this issue?

CodePudding user response:

Because you're comparing string with datetime.date object. Like comparing

23 > "hello world" 

Try converting the string received from the previous method. Follow the another discussion

CodePudding user response:

This:

another_date = request.POST.get("date")

is giving you date in string format, like "2022-06-16", and datetime.date gives datetime.date(2022, 06, 16). You cannot compare it like that, you have to transform one to type of another (or the other way).

I suggest:

current_date = date.today().strftime("%Y-%m-%d")
another_date = request.POST.get("date")

I assume 'date' looks like year-month-day.

CodePudding user response:

Date fields from a form will give you a string value which is formatted in YY-MM-DD. This format which is a string str, cannot be compared to a datetime object. Hence, the reason for getting the error you got:

'<' not supported between instances of 'datetime.date' and 'str'

You could create a reusable function to compare the dates like:

def dates_equal(d1, d2):
     if d1 == d2:
          return True
     else:
          return False

Then somewhere in your code, you can call it like...

current_date = date.today()

# Getting the string version of the date object
current_date = current_date.strftime("%Y-%m-%d")

# I am getting this another date from a html input type date
another_date = request.POST.get("date")

# Calling the date comparing method here...
if dates_equal(current_date, another_date):
     # do something here...
else:
     # do something else...
  • Related