1970年构造ObjectId()时间戳为负
import time import datetime from bson.objectid import ObjectId from collections import Iterator class MyIter(Iterator): def __next__(self): return ObjectId() published_at = datetime.datetime.now() print(published_at) print(published_at.timetuple()) print(time.mktime(published_at.timetuple())) print(int(time.mktime(published_at.timetuple()))) # 2019-04-04 17:36:45.322429 # time.struct_time(tm_year=2019, tm_mon=4, tm_mday=4, tm_hour=17, tm_min=36, tm_sec=45, tm_wday=3, tm_yday=94, tm_isdst=-1) # 1554370644.0 # 1554370671 oid = MyIter().__next__() print(str(oid)) print(str(oid)[8:]) # <__main__.MyIter object at 0x10319e358> # _.MyIter object at 0x10319e358> print('{:02x}'.format(int(time.mktime(published_at.timetuple())))) # 5ca5d16f origin_time = "1970-01-01 00:00:00" origin_time = datetime.datetime.strptime(origin_time, "%Y-%m-%d %H:%M:%S") print(origin_time) print(type(origin_time)) # published_at=创建时间 published_at = datetime.datetime.now() published_at = "1970-01-01 00:00:00" published_at = datetime.datetime.strptime(published_at, "%Y-%m-%d %H:%M:%S") if published_at > origin_time: print("yes") _id = ObjectId('{:02x}'.format(int(time.mktime(published_at.timetuple()))) + str(oid)[8:]) print('_id01: ', _id) else: published_at = datetime.datetime.now() _id = ObjectId('{:02x}'.format(int(time.mktime(published_at.timetuple()))) + str(oid)[8:]) print('_id02: ', _id) # Traceback (most recent call last): # File "/Users/Alex/Desktop/toc_backend/aaa_xwk/create_objectid.py", line 36, in <module> # _id = ObjectId('{:02x}'.format(int(time.mktime(published_at.timetuple()))) + str(oid)[8:]) # File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/bson/objectid.py", line 125, in __init__ # self.__validate(oid) # File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/bson/objectid.py", line 221, in __validate # _raise_invalid_id(oid) # File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/bson/objectid.py", line 67, in _raise_invalid_id # " or a 24-character hex string" % oid) # bson.errors.InvalidId: '-7080f71ec31bb7b87df9' is not a valid ObjectId, it must be a 12-byte input or a 24-character hex string