【问题标题】:Convert MongoDB Date format to String in Python (without using dateToString)在 Python 中将 MongoDB 日期格式转换为字符串(不使用 dateToString)
【发布时间】:2016-09-23 08:34:29
【问题描述】:

我想将 MongoDB 日期对象转换为字符串。

但是,我无法使用“dateToString”运算符,因为我运行的是 MongoDB 2.6,目前没有升级选项。

我应该改用什么?

查询:

computer = db['cmp_host'].aggregate([
        {"$project":{
            "u_ipv4": "$addresses.ipv4",
            #"u_updated_timestamp": "$last_seen",
            #"u_updated_timestamp": { $dateToString: { format: "%Y-%m-%d", date: "$last_seen" } }
            }
         }
        ])

当前 MongoDB 日期格式(需要转换为人类可读的字符串):

datetime.datetime(2016, 9, 2, 12, 5, 18, 521000)

【问题讨论】:

    标签: python mongodb date


    【解决方案1】:

    datetime.datetime(2016, 9, 2, 12, 5, 18, 521000) 是 Python 日期时间类型,而不是 MongoDB 的。

    要将其转换为字符串,可以使用 Python datetime 的 strftime() 方法。例如:

    >>> d = datetime.datetime(2016, 9, 2, 12, 5, 18, 521000)
    
    >>> d.strftime('%Y-%m-%d')
    '2016-09-02'
    
    >>> d.strftime('%c')
    'Fri Sep  2 12:05:18 2016'
    

    strftime()的完整描述在这里:https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior

    【讨论】:

    • 谢谢,知道在 mongodb 查询的上下文中我会如何做到这一点吗?谢谢!
    • 不幸的是,我认为在 MongoDB 2.6 中没有任何方法可以做到这一点。如果升级不是一种选择,那么对结果进行后处理将是最简单的解决方案。不过,我还是鼓励您升级,因为 MongoDB 2.6 即将结束生命周期并且不会很快得到支持。
    猜你喜欢
    • 2016-06-12
    • 1970-01-01
    • 2021-02-03
    • 2019-04-30
    • 2020-07-25
    • 1970-01-01
    • 2013-12-28
    • 1970-01-01
    • 2018-04-06
    相关资源
    最近更新 更多