Let’s say my database is called “data” and its second column is called “datetime”. The format of my datetime is “7/22/2011 12:00:00”. If I want to get the the information between 12:00 and 13:00 today, how do I do that?
SELECT * FROM data WHERE
strftime('%m/%d/%Y %H:%M:%S', datetime) > strftime('%m/%d/%Y %H:%M:%S', '7/22/2011 12:00:00')
AND
strftime('%m/%d/%Y %H:%M:%S', datetime) < strftime('%m/%d/%Y %H:%M:%S', '7/22/2011 13:00:00')
doesn’t do the trick.
I got this wrong — shame on me.
strftimewill only read in ISO 8601 (or timestamp/julian) values. The format specified doesn’t apply to the the input — it is only for the output value.For this reason the data in the database must still have a natural ordering to be sorted. The suggested formats are ISO 8601 (string), timestamp (integer), and julian-date (float). Using a date like
m/d/yin the database won’t work for range compares because it fails to adhere to natural ordering.strftimeand friends simply allow generation of one of the values useful for the comparison — e.g. can convert from ISO 8601/timestamp/julian input to custom/ISO 8601/timestamp/julian-date. They can not directly convert from a custom value though.The easiest way to fix the database is probably to use a language like Python to write a script for the conversion of existing data. A small Java program could also be written taking advantage of SimpleDateFormat to parse the existing values and write them back using one of the recommended types.
Historical:
Try it in pieces from the console (this will enable must faster experimenting with the query) — the first conditional then the second. What returns what and why? Once each piece is working then putting them to-gether will work.
There are multiple strftime format mistakes — see Date and Time for the formats and check the strings again 🙂 Also, if using a saner date format (ISO 8601), could just use
datetimeand not worry about specifying the format explicitly. ISO 8601 values are is also lexically sortable as strings — an added advantage.I am not sure how the Java SQLite adatper will handle a Date when passed as a parameter to a parametrized query (parametrized queries really should be used) … but in any case this is a secondary issue to the current behavior observed.
Happy coding.