将选定的日期时间转换为 sqlalchemy 中的日期 [英] convert selected datetime to date in sqlalchemy

查看:21
本文介绍了将选定的日期时间转换为 sqlalchemy 中的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个测试记录数据库,其中一列test_time"定义为日期时间.我想查询有多少个不同的日期,因为我想根据日期将测试结果转储到 csv.我现在有以下内容:

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())

但这给了我一个日期时间而不是日期的列表.当然我可以在 Python 中转换它,但是当我使用 sqlite 时.我做了这个SELECT DISTINCT DATE(test_time) FROM Test_Table.我无法想出 sqlalchemy 中的等价物.

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.

推荐答案

那将是使用 cast() 表达式:

That would be by using the cast() expression:

from sqlalchemy import cast, Date

distinct_dates = session.query(cast(Test_Table.test_time, Date)).distinct().all()

快捷方法:

distinct_dates = session.query(Test_Table.test_time.cast(Date)).distinct().all()

如果使用 SQLite,试一试:

and if using SQLite, give this a shot:

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

这篇关于将选定的日期时间转换为 sqlalchemy 中的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆