【问题标题】:Query issue in pymongopymongo中的查询问题
【发布时间】:2017-10-21 07:59:00
【问题描述】:

我在通过 python 查找具有今天日期函数的文档时遇到了一些问题。

我使用以下函数:

datetime.datetime.now().date().strftime('%Y-%m-%d') 

它给出以下值:2017-05-21

但是,我的文档 (mongo) 中的值在其周围附加了双字符串,如下所示:"2017-05-21"

因此,在我的 pymongo 查询中准确填写上述字符串(“2017-05-21”)就像一个魅力。但是,我需要 datetime 函数的动态性,但不幸的是,这与查询所需的双引号日期字符串不匹配。

有人知道解决方法吗?我已经尝试过替换功能等。它要么在单引号内创建双引号,要么什么都不做。

【问题讨论】:

    标签: python mongodb datetime pymongo


    【解决方案1】:

    听起来您的 MongoDB 文档插入不正确,使用文本作为日期字段而不是 BSON 日期时间。

    PyMongo 会自动在 Python 日期时间和 BSON 日期时间之间进行转换,因此您可以像这样插入包含 BSON 日期时间的文档:

    dt = datetime.datetime.utcnow()
    collection.insert_one({'myDate': dt})
    

    证明日期比较现在可以这样工作:

    # There is a document with myDate in the past, now.
    print(collection.find_one({'myDate': {'$lt': datetime.datetime.utcnow()}}))
    # No document with myDate in the future.
    print(collection.find_one({'myDate': {'$gt': datetime.datetime.utcnow()}}))
    

    【讨论】:

    • 谢谢 A. Jesse,我还没有尝试过您的解决方案,但已经感觉到它会起作用。非常感谢!!
    猜你喜欢
    • 2018-07-06
    • 2013-03-07
    • 2023-03-14
    • 2020-04-16
    • 2010-12-17
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 2020-05-03
    相关资源
    最近更新 更多