potato99
potato99

Reputation: 27

Filter sqlalchemy sqlite datetime column by date

I have a datetime column in a database (Named TestBase) like so:

INDEX   DateTimeColumn
...     ...
1241    2010-07-26 07:04:05 
1242    2010-07-26 07:04:07 
1243    2010-07-26 07:04:12 
1244    2010-07-27 10:59:53

I want to get all the unique days in the column.

However, using the distinct function in sqlalchemy as such: distinct(TestBase.DateTimeColumn) does not work. As it takes the time within the timestamp into account and considers every entry to be unique.

How do I write a query which ignores the time within a timestamp and just returns the list of unique dates?

Upvotes: 1

Views: 476

Answers (1)

snakecharmerb
snakecharmerb

Reputation: 55600

Use the database's DATE function to truncate the datetime to a date. The DATE function is accessed through sqlalchemy.sql.func:

from sqlalchemy import sql

q = session.query(sql.func.date(MyModel.datetimecolumn))

Upvotes: 3

Related Questions