func.Date returns str instead of date object in sqlite
See original GitHub issueWe know that sqlite does not have date or datetime functionalities, and uses strings instead. And this functionality is provided by SQLAlchemy.
It works great on simple queries like this:
dates = (db.session.query(Session.starts_at)
.filter_by(state='accepted')
.distinct().all())
This returns datetime objects - [(datetime.datetime(2019, 10, 15, 10, 25, 46),), (datetime.datetime(2019, 10, 15, 11, 30),), (datetime.datetime(2019, 10, 16, 9, 15, 30),), (datetime.datetime(2019, 10, 16, 11, 30, 30),)]
Let’s say we want to select distinct dates and we use CAST
dates = (db.session.query(cast(Session.starts_at, DATE))
.filter_by(state='accepted')
.distinct(),all())
This fails with the error:
Couldn't parse date string '2019' - value is not a string.
This is expected as it relies on sqlite CAST which returns year for some reason.
The closest I got to getting correct result(and I did get correct results), was using func.Date
dates = (db.session.query(func.date(Session.starts_at))
.filter_by(state='accepted')
.distinct().all())
This returns correct results - [('2019-10-15',), ('2019-10-16',)]
But, as we can see, they are str
s
Is there anyway SQLAlchemy can convert them in date objects as func.Date
is SQLAlchemy internal and it already has https://docs.sqlalchemy.org/en/13/dialects/sqlite.html#sqlalchemy.dialects.sqlite.DATE which has all the logic needed for parsing this date.
So, can we get [(datetime.date(2019, 10, 15),), (datetime.date(2019, 10, 16),)]
as result? Am I missing something or is there any workaround for this?
P.S. I don’t know if https://gist.github.com/zzzeek/7470863 was related to this, but it doesn’t help as well.
Thanks
Issue Analytics
- State:
- Created 4 years ago
- Comments:5 (3 by maintainers)
you want to call the func like this:
that will tell it the return type is Date and it will do the coercion
the docs are horrible for func, there’s nothing there about how to use it at all, nor is there any real usage guidelines or parameter descriptions. people know this from the tutorial at https://docs.sqlalchemy.org/en/13/core/tutorial.html#functions but the docstrings should be pointing back there. all of them should be a little more clear that type_ is fairly important for cases like this.