[英]Python SQLAlchemy - TypeError: '>' not supported between instances of 'type' and 'datetime.datetime'
I have a query that looks at a table in my MySQL database and I'm looking to retrieve the data between two datetimes.我有一个查询,它查看我的 MySQL 数据库中的一个表,我希望检索两个日期时间之间的数据。
At the moment, I get the session and the Table properties assigned just fine:目前,我得到了会话和表属性分配得很好:
>>> session
<sqlalchemy.orm.session.Session object at 0x000001EC64FF6EF0>
>>> table
Table('txt_raw1', MetaData(bind=None), Column('datetime', DATETIME(fsp=6), table=<txt_raw1>, nullable=False), and some extra stuff...
I then begin to form the query and so far, so good:然后我开始形成查询,到目前为止,很好:
>>> query = session.query(table)
>>> query.filter_by(Name='Jose')
>>> query
<sqlalchemy.orm.query.Query object at 0x000001EC50281A90>
However, when I try to filter by the datetime column, I get an error:但是,当我尝试按日期时间列进行过滤时,出现错误:
>>> start_date = datetime.strptime('2020-11-10','%Y-%m-%d')
>>> start_date
datetime.datetime(2020, 11, 10, 0, 0)
query.filter_by(datetime > start_date)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '>' not supported between instances of 'type' and 'datetime.datetime'
Odd thing to me, though, when I checked the first set of data in the query instance, it is of the datetime.datetime format但是,对我来说奇怪的是,当我检查查询实例中的第一组数据时,它是datetime.datetime 格式
>>> query[0][0]
datetime.datetime(2019, 11, 16, 1, 43, 54, 192000)
Does anyone have any suggestions to how I can filter by datetime using the type datetime.datetime?有没有人对我如何使用 datetime.datetime 类型按日期时间进行过滤有任何建议?
I think datetime
is recognize as type
not table column name in query.filter_by(datetime > start_date)
code.我认为
datetime
在query.filter_by(datetime > start_date)
代码中被识别为type
而不是表列名。
Use filter
instead of filter_by
使用
filter
而不是filter_by
query.filter(Table.datetime > start_date)
face palm脸掌
Wasn't too smart using datetime as the column header in the MySQL database使用日期时间作为 MySQL 数据库中的列标题不太聪明
I was able to get the filter by using the table.c operator:我能够通过使用 table.c 运算符来获取过滤器:
>>> query.filter(table.c.datetime > start_date)
<sqlalchemy.orm.query.Query object at 0x000001EC6502C940>
Note, I used query.filter
instead of query.filter_by
注意,我使用了
query.filter
而不是query.filter_by
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.