Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django check if date from post is between two dates from model

Tags:

python

django

I'm not really experienced in Django, but now I am trying to develop simple project with model class like this:

class FacebookEvent(models.Model):
   start_time = models.DateTimeField(null=True)
   end_time = models.DateTimeField(null=True)

In view file - there's no problem when I want to get all objects where start_time is today, tomorrow or in any other date range (including hours):

my_date= request.POST.get('my_date','') # for eg. 2015-10-26
events = FacebookEvent.objects.all().filter(start_time__range=
    (datetime.combine(my_date,(datetime.min).time()), datetime.combine(my_date,(datetime.max).time()))).order_by('start_time')

but now i have to check if requested date (my_date) is between start_time and end_time from model. I just have to do the same what I was doing before, but a little bit inversely...

It took me few hours, but still I can't find any concept how to solve this problem. Anybody have any idea?

Thanks in advance.

like image 790
StoreCat Avatar asked Sep 26 '22 09:09

StoreCat


2 Answers

Im not sure if I understand the question.

If you have a model instance and a date:

First you need to convert your date to a datetime.datetime object

from dateutil.parser import parse
my_date= request.POST.get('my_date','')
mdate = parse(mydate)

Then you can use mdate to do logical comparisons. i.e: mdate > fbEvent.start_time

If you want model instances between dates

 mdate = parse(mydate)   
events = FacebookEvent.objects.filter(start_time__gt=mdate, end_time__lt=mdate)
like image 65
jdcaballerov Avatar answered Sep 30 '22 05:09

jdcaballerov


you can do like:

from datetime import datetime
my_date= request.POST.get('my_date','') # for eg. 2015-10-26
my_date = datetime.strptime(my_date, "%Y-%m-%d")

events = FacebookEvent.objects.filter(start_time__lt=my_date, end_time__gt=my_date).order_by('start_time')
like image 35
Anush Devendra Avatar answered Sep 30 '22 05:09

Anush Devendra