我正在尝试从 ObjectID 获取时间戳,但 Mongo 一直给我这个错误。我错过了进口吗?将时间戳转换为标准日期格式的最佳方法是什么?
video['date'] = video['_id'].getTimeStamp()
这个答案是基于 python 和 Django 的。
在使用之前请generation_time
注意,generation_time
它将转换为 UTC(世界时间),这可能会提前或落后于您当前的时区,因此如果您在项目设置中使用本地时间来保存时间戳,您可能会看到时间差异对象。对我来说,相差5.5小时。所以根据你的时区调整时间。
示例:ObjectId('5c51aca67c76124020edbbaf')
这个对象的实际创建时间是,
但是datetime.datetime(2019, 1, 30, 19, 24, 28, 73000)
当我使用generation_time
它生成它的时间时,它落后了 5.5 小时。
In [10]: from bson import ObjectId
In [11]: ObjectId('5c51aca67c76124020edbbaf').generation_time
Out[11]: datetime.datetime(2019, 1, 30, 13, 54, 46, tzinfo=<bson.tz_util.FixedOffset object at 0x102461128>)
由于我们从文档的 object_id 中获取 UTC 时间,因此要转换为您的当地时间,您可以做的是......
document['_id'].generation_time #(gives the generation/creation time of the object id in UTC.)
utc=document['_id'].generation_time
hours_added = datetime.timedelta(hours = 4)` #(Suppose utc+4 is my local time.)
local_time=utc+hours_added