Piyush S. Wanare
Piyush S. Wanare

Reputation: 4933

How to compare two Datetime field in Django

I have used datetime.datetime.now() for storing datefield in my model which is saved as 2016-06-27 15:21:17.248951+05:30. Now I want to compare the datefield with the datetime value getting from the frontend, like Thu May 26 2016 00:00:00 GMT 0530 (IST). How should Django query the model to compare both datefields?

# models.py

datefield = models.DateTimeField(blank=True,null=True)

I have tried converting datefield getting from frontend by using split() and remove() function of Python to create it in format as 2016-06-27 13:25:35.

But still no solution and getting Null even I am comparing same date value like this (2016-06-27 13:25:35) value with this (2016-06-27 12:36:34.898593+00) value, as date in both values are same.

I have checked it using simple Django query as follows:

company_details.objects.filter(datefield=datefield).only('par1','par2',...)

Upvotes: 7

Views: 11907

Answers (2)

C14L
C14L

Reputation: 12558

Once you have converted the date from the front end into a ISO format like 2016-06-27 13:25:35, you can use it to query the model with one of these

Model.objects.filter(date_created__startswith=today)
Model.objects.filter(date_created__contains=today)

It works too if you are only looking to filter for a certain date like 2016-06-27.

Model.objects.filter(date_created__startswith=date(2016, 6, 27))

To parse the date string you are getting from the frontend, there are two options.

If your date string is well-formatted, you can simply parse it with for example datestring.strftime('%Y-%m-%d %H:%M:%S') to get a datetime() object.

If your date string is unreliable and may be formatted in different ways that you can't predict, I would recommend to using DateUtil. It comes with a parser that will try to convert any string into a datetime, for example

>>> from dateutil.parser import parse
>>> parse("Today is January 1, 2047 at 8:21:00AM", fuzzy_with_tokens=True)
(datetime.datetime(2011, 1, 1, 8, 21), (u'Today is ', u' ', u'at '))

Upvotes: 2

Rahul K P
Rahul K P

Reputation: 16081

Compare the date and time like this. Just give the variable like this '%Y-%m-%d %H:%M:%S' as much you want.

In [1]: from datetime import datetime
In [2]: past = datetime.now()
In [3]: present = datetime.now()
In [4]: present.strftime('%Y-%m-%d %H:%M:%S') == past.strftime('%Y-%m-%d %H:%M:%S')
Out[17]: False
In [5]: present.strftime('%Y-%m-%d %H:%M') == past.strftime('%Y-%m-%d %H:%M')
Out[2]: True

If you want to compare only the date use like this.

if present.date() == past.date():
    #Do your stuff

Upvotes: 2

Related Questions