如何将pandas DataFrame的datetime索引作为具有isoDate类型的字段插入mongodb

时间:2015-11-30 08:04:58

标签: python mongodb pandas datetime-format

我有一个类型为pandas.core.frame.DataFrame的数据框 喜欢:

<?php 
 $catPost = get_posts(get_cat_ID("NameOfTheCategory")); //change this
   foreach ($catPost as $post) : setup_postdata($post); ?>
       <div>
             <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> 
             <p><?php the_content(); ?></p>
       </div>
<?php  endforeach;?>

df.index

              open  high  close   low    volume     amount
 date                                                    
 2015-11-27  8.10  8.16   7.35  7.34  37877648  294274400
 2015-11-26  8.03  8.44   8.16  8.00  45933600  378897088
 2015-11-25  7.95  8.03   7.99  7.89  21255886  169172176
 2015-11-24  7.95  8.18   8.04  7.85  24808112  199120256
 2015-11-23  8.24  8.29   7.95  7.93  29176848  236019264

如何使用DatetimeIndex(['2015-11-27', '2015-11-26', '2015-11-25', '2015-11-24', '2015-11-23', '2015-11-20', '2015-11-19', '2015-11-18', '2015-11-17', '2015-11-16', ... '2014-12-12', '2014-12-11', '2014-12-10', '2014-12-09', '2014-12-08', '2014-12-05', '2014-12-04', '2014-12-03', '2014-12-02', '2014-12-01'], dtype='datetime64[ns]', name=u'date', length=193, freq=None) 格式的date.index字段将df插入mongodb,而不是datatime64 [ns] / timestamps?

1 个答案:

答案 0 :(得分:2)

我已经困扰了很长时间,但我终于找到了办法。 这取决于我们插入mongod的方式。 我以这种方式插入mongod:

records = json.loads(DataFrame.T.to_json()).values()
collection.insert_many(records)

我们需要了解这种方法会将DataFrame时间转换为datatime64 [ns] / timestamps。

print records[0]
{u'dtime': 1407076151000L,u'olddtime': u'2014/8/3 14:29:11'}

我们可以看到它节省了数字时间和DateTime作为字符串的时间。所以我们需要更改记录:

for row in records:
    row['olddtime'] = datetime.datetime.strptime(row['olddtime'], "%Y/%m/%d %H:%M:%S")

然后我们打印出来:

{u'olddtime': datetime.datetime(2014, 8, 3, 14, 29, 11), u'dtime': 1407076151000L}

最后我们这样做:

collection.insert_many(records)

那没关系!