【问题标题】:MongoDB/pymongo calculate difference of two times in minutesMongoDB/pymongo 以分钟计算两次的差异
【发布时间】:2018-08-19 01:49:44
【问题描述】:

我正在尝试计算 mongodb 中两个时间戳之间的差异。

使用 MySQL 可以很容易地使用这个查询来实现

SELECT ROUND((TIME_TO_SEC(NOW()) - TIME_TO_SEC(lastseen))/60) AS minutes 其中 lastseen 是一个时间戳列。

这是我的架构:

{
    "_id" : ObjectId("5aa329cb0b717a0f637b0937"),
    "username" : "admin@mans.com",
    "token" : "1085bbc68a",
    "realname" : "Administrator",
    "lastseen" : ISODate("2018-03-09T19:41:47.552Z")
}

如何获取文档中lastseendatetime.datetime.now() 之间的时间差(以分钟为单位)?

【问题讨论】:

    标签: python mongodb pymongo


    【解决方案1】:

    $subtract aggregation query operator 可用于查找两个日期的差异。 例如

    query = [{
        '$project': {
            'username': 1,
            'date_diff_mins': { 
                 '$divide': [
                     {'$subtract': [datetime.now(), '$lastseen']},
                     1000 * 60
                 ] 
            } 
        }
    }]
    db.collection.aggregate(query)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-12
      • 2021-11-14
      • 2012-10-26
      • 2013-09-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多