Python orm 日期时间问题

标签 python mysql-python peewee

我在一个带有日期时间字段的非常大的数据库中有一个 Peewee 数据库模型 Products。 当我想选择带有(插入时间大于现在())的文章时,查询将永远挂起。

class Products(BaseModel):
    id = IntegerField()
    name= CharField()
    inserted = DateTimeField()

class Meta:
    db_table = 'products'

Products.select().where(Products.inserted >datetime(2013, 04, 03, 14, 52, 50).strftime("%Y-%m-%d %H:%M:%S"))

我不确定是因为数据库大小(大于 10 GB)还是因为查询样式。

我应该像这样使用日期时间 datetime(2013, 04, 03, 14, 52, 50) 还是“2013-04-03 14:52:50”?

最佳答案

Peewee 将接受 datetime 对象作为输入,因此您无需进行任何转换。我猜问题是您缺少索引。

尝试:

class Products(BaseModel):
    id = IntegerField(primary_key=True) # <-- You should specify a Primary Key
    name= CharField()
    inserted = DateTimeField(index=True) # <-- this should be an index

Products.select().where(Products.inserted >datetime(2013, 04, 03, 14, 52, 50))

如果您的表已经存在,您可以使用 python shell 以编程方式添加索引:

# assuming your db is named "db"
db.create_index(Products, [Products.inserted])

关于Python orm 日期时间问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15790553/

相关文章:

Mysql 1366错误-使用utf8mb4编码

mysql - Peewee 在 sqlite 而不是 mysql 中创建表

python - Peewee 原子更新复杂逻辑

python - peewee IntegrityError : NOT NULL constraint failed: terms.sets_id

python - 尝试使用 pdfminer.6 提取文本时如何修复 'UnicodeDecodeError'?

python - 使用 Python 3.4 的 Openshift 自定义墨盒

python - Pandas str.extract 可一起用于过滤数据和交叉表吗?

Mysql根据小时累计求和

python - 为什么非常小的 checkinterval 不会减慢 python3 中 CPU 密集型多线程的速度?

python - 使用 python 从 mysql 行 fetchall 创建具有多个值的嵌套字典