0

If i want to apply check like this in views.py:

now=timezone.now()
if now <= arrival:
        messages.error(request, 'Please enter valid Time')
        return redirect('add_schedule') 

where arrival is datetime field in models.py

It gives error of '<=' not supported between instances of 'datetime.datetime' and 'str', How can i apply this check?

None
  • 35
  • 6
  • 4
    Does this answer your question? [How to compare dates in Django templates](https://stackoverflow.com/questions/3798812/how-to-compare-dates-in-django-templates) – doğukan Jul 06 '20 at 16:54

1 Answers1

2

well there are multiple ways for this.

1- the best and easiest one is to use datetime function __ gt __() which means "Greater Than":

import datetime
now = datetime.datetime.now()
if arrival.__gt__(now):
    messages.error(request, 'Please enter valid Time')
    return redirect('add_schedule')

2- but alternatively you can use timestamps to compare two dates:

currentTimestamp = now.timestamp()
arrivalTimestamp = arrival.timestamp()
if arrivalTimestamp > currentTimestamp :
    messages.error(request, 'Please enter valid Time')
    return redirect('add_schedule') 

Note: the second way use more ram and possibly have less speed

babak gholamirad
  • 407
  • 4
  • 10