pymongo 将 mongoDB 日期转换为 python 日期时间

pymongo convert mongoDB date to python datetime

我有一个 MongoDB 数据库,其中有一些时间条目(例如,某些实体的创建日期)。当我在数据库中查看它们时,它们似乎是 64 位整数 BSON 格式。数据库条目最初是使用 C#(ASP.NET 核心)创建的,使用以下表示形式:

[BsonRepresentation(MongoDB.Bson.BsonType.Decimal128)]

我想使用 Python 脚本访问该数据库以获取一些统计信息。我可以使用 pymongo 在我的 python 代码中获取该条目。典型值如下所示:[637013892303590646, 0]。如何将其转换为人类可读的 python datetime 值?

如果我打印从 pymongo 获得的变量类型,它会显示:bson.int64.Int64

我在此处查看了 bson 模块文档:https://api.mongodb.com/python/current/api/bson/index.html,但找不到合适的函数来进行转换。有人可以告诉我正确的调用以将 bson.int64.Int64 转换为 datetime 值吗?

谢谢!

您的数据在ticks;定义为:

The value of this property represents the number of 100-nanosecond intervals that have elapsed since 12:00:00 midnight, January 1, 0001 in the Gregorian calendar, which represents MinValue. It does not include the number of ticks that are attributable to leap seconds. If the DateTime object has its Kind property set to Local, its ticks represent the time elapsed time since 12:00:00 midnight, January 1, 0001 in the local time as specified by the current time zone setting. If the DateTime object has its Kind property set to Utc, its ticks represent the time elapsed time since 12:00:00 midnight, January 1, 0001 in the Coordinated Universal Time. If the DateTime object has its Kind property set to Unspecified, its ticks represent the time elapsed time since 12:00:00 midnight, January 1, 0001 in the unknown time zone.

因此我们可以编写一个 ticks_to_datetime() 函数,该函数使用基于 0001 年 1 月 1 日午夜的 timedelta,除以 10 以将 100 纳秒转换为微秒。

import pymongo
from datetime import datetime, timedelta
from bson import Int64

def ticks_to_datetime(ticks):
    return datetime(1, 1, 1) + timedelta(microseconds=ticks / 10)

mydb = pymongo.MongoClient()['mydatabase']

mydb.mycollection.insert_one({'old_time': [Int64(637013892303590646), 0]})
record = mydb.mycollection.find_one({})
old_time = record['old_time'][0]
new_time = ticks_to_datetime(old_time)
print(new_time)

给出:

2019-08-14 14:20:30.359062