Sunday, May 22, 2016

Query and order by time difference of a specified time.

Hi.
I am looking for a way to find a row which is closest to a specified
point in time, no matter if the row is before or after.

In plain SQL (using SQLite as example), it's very easy to do;

SELECT *,
abs(
strftime('%s','2015-05-21 23:05:00') - strftime('%s',`created`)
) AS timdif
FROM myapp_posts f ORDER BY timdif LIMIT 10;


The above snippet converts the specified date and field to epoch
seconds, subtracts them and then sorts the query according to the
difference.

Is it possible do this in Django without resorting to raw queries?

Thank you.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/57425C4C.1050500%40x76.eu.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment