Click here to Skip to main content
15,881,281 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello friends,

I am trying to fetch records of certain date range in Django, i googled to see if i can get some solution but nothing seems to work.

Date time saved in database is "May 7, 2018, 11:33 a.m." and the date format i get from html is in "2018-05-01". Because the date format is different, i am not able to fetch records in range. Please help. Thank you.

What I have tried:

Python
q1 = request.POST.get('q1') #2018-05-01
q2 = request.POST.get('q2') #2018-05-10 

ModelClass.objects.filter(created_date__range=(q1, q2))

#created_date field has date in format - "May 7, 2018, 11:33 a.m."
Posted
Updated 6-May-18 22:10pm

1 solution

The datetime is not stored in the format "May 7, 2018, 11:33 a.m." in the database. It is returned formatted in that way by some function used to query the databse.

SQLite knows three different formats to specify dates and times:
TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.SSS").
REAL as Julian day numbers, the number of days since noon in Greenwich on November 24, 4714 B.C. according to the proleptic Gregorian calendar.
INTEGER as Unix Time, the number of seconds since 1970-01-01 00:00:00 UTC.
So you have to use one of these formats (probably the TEXT format in your case). There are also helper functions to format dates: SQLite Query Language: Date And Time Functions[^].

Your posted dates are already in the ISO 8601 format. So your code should work without modifications.
 
Share this answer
 
Comments
codeXprojectX 7-May-18 5:12am    
Thank you so much Jochen :)

Working :P

Thanks for the reply.
Jochen Arndt 7-May-18 5:14am    
You are welcome and thank you for accepting my solution.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900