None
None

Reputation: 35

How to compare now and datetime field in Django?

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?

Upvotes: 0

Views: 241

Answers (1)

babak gholamirad
babak gholamirad

Reputation: 568

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

Upvotes: 2

Related Questions