convert selected datetime to date in sqlalchemy

匿名 (未验证) 提交于 2019-12-03 02:26:02

问题:

I have a database of test records with one column 'test_time' defined as datetime. I want to query how many distinct dates there are as I want to dump test results to csv according to dates. I now have the following:

distinct_dates = list(session.query(Test_Table.test_time).distinct()) 

But this gives me a list of datetime not date. Certainly I can convert it in Python but when I am using sqlite. I did this SELECT DISTINCT DATE(test_time) FROM Test_Table. I cannot come up with the equivalent in sqlalchemy.

回答1:

That would be by using the "cast" expression:

distinct_dates = list(session.query(cast(Test_Table.test_time, DATE)).distinct()) 

EDIT: Ok, let's give this a shot:

distinct_dates = list(session.query(func.DATE(Test_Table.test_time)).distinct()) 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!