在 pymongo 中,您可以执行以下操作从时间创建 OID:
dummy_id = ObjectId.from_datetime(time)
蒙古有类似的东西吗?
我看到有一个“ bson_oid_get_time_t() ”函数,但是有没有这个的反向函数,如果没有,如何在C中实现?
在 pymongo 中,您可以执行以下操作从时间创建 OID:
dummy_id = ObjectId.from_datetime(time)
蒙古有类似的东西吗?
我看到有一个“ bson_oid_get_time_t() ”函数,但是有没有这个的反向函数,如果没有,如何在C中实现?
我不相信有一个反向功能,但你应该很容易使用默认构造函数生成自己的构造函数并“修复”时间。
这是我创建对象 ID 的示例。
然后我为 2014 年 12 月 25 日创建一个时间戳,并将 OID 修改为该日期。
#include <time.h>
#include <bson.h>
int
main (int argc,
char *argv[])
{
time_t oid_thinks_time; //what time does the OID think it is
bson_oid_t oid;
bson_oid_t *oid_pointer = &oid;
bson_oid_init (&oid, NULL); // get a standard ObjectId
oid_thinks_time = bson_oid_get_time_t (&oid); //It was just made
printf ("The OID was generated at %u\n", (unsigned) oid_thinks_time); //prove it
time_t ts = time(NULL); //make a new time
struct tm * timeinfo = localtime(&ts);
timeinfo->tm_year = 2014-1900; //-1900 because time.h
timeinfo->tm_mon = 12 - 1; // time.h off by one (starts at 0)
timeinfo->tm_mday = 25;
ts = mktime(timeinfo); // create the time
u_int32_t ts_uint = (uint32_t)ts;
ts_uint = BSON_UINT32_TO_BE (ts_uint); //BSON wants big endian time
memcpy (&oid_pointer->bytes[0], &ts_uint, sizeof (ts_uint)); //overwrite the first 4 bytes with user selected time
oid_thinks_time = bson_oid_get_time_t (&oid);
printf ("The OID was fixed to time %u\n", (unsigned) oid_thinks_time);//prove it
}
这段代码的输出是:
The OID was generated at 1491238015
The OID was fixed to time 1419526015