Python 将时间戳插入Mongodb
我正在尝试使用PyMongo将Pandas数据帧插入MongodbPython 将时间戳插入Mongodb,python,mongodb,pandas,pymongo,Python,Mongodb,Pandas,Pymongo,我正在尝试使用PyMongo将Pandas数据帧插入Mongodb df.head() 因为熊猫数据帧的索引是DatetimeIndex,所以将数据帧转换为dict,并将其插入Mongodb: db.testCollection.insert( df.T.to_dict() ) 导致错误: InvalidDocument: documents must have only string keys, key was Timestamp('2016-04-07 09:30:00') 我们如何
df.head()
因为熊猫数据帧的索引是DatetimeIndex
,所以将数据帧转换为dict
,并将其插入Mongodb:
db.testCollection.insert( df.T.to_dict() )
导致错误:
InvalidDocument: documents must have only string keys, key was Timestamp('2016-04-07 09:30:00')
我们如何将
DatetimeIndex
转换为其他可以插入Mongodb的内容,然后在从Mongodb读取时仍然能够转换回DatetimeIndex?解决方案是,在尝试存储到Mongodb之前,将索引转换为str
,如下所示:
>> df.index = df.index.astype(str)
>> db.testCollection.insert(df.T.to_dict())
稍后再次从db中读取数据时,可以将索引转换为时间戳:
>> df.index = pd.to_datetime(df.index)
我希望这有帮助