SQLITE Order Column in DateTime closest to furthest Python

Question:

I am putting DateTimes into my SQlite DB, however, I need them to be ordered from the closest to the current date to the farthest. I do not get a DateTime datatype option for my SQlite column. So how can I order them? I cannot find anything online, and nothing i tried has worked so far.

Asked By: user15473634

||

Answers:

You’re right that SQLite does not have a native datetime data type, however it can store such data:

SQLite does not have a storage class set aside for storing dates and/or times. Instead, the built-in Date And Time Functions of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values:

  • 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.

All of these options will sort as you’d expect. Pick the type that fits your use case best.

Tables in SQLite (and other relational databases) are ordered however the database engine finds most convenient. You can impose an order on the results when you query, e.g.

SELECT *
FROM my_table
ORDER BY created_at DESC;
Answered By: Chris
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.