【问题标题】:How to convert JSON inserted created_at field in MongoDB to datetime objects in Python如何将 MongoDB 中的 JSON 插入 created_at 字段转换为 Python 中的日期时间对象
【发布时间】:2013-12-20 06:05:43
【问题描述】:

我已经从 twitter 挖掘数据好几个星期了,没想到我直接将它作为 JSON 结构直接插入到 MongoDB。

这似乎导致了“created_at”字段为字符串格式而不是日期时间的问题。如果我想在特定日期之间从集合中撤回推文,这基本上会使我的索引变得无用。

我正在使用 python tweepy 包,并且一直将 json 推文插入到 mongodb 中,如下所示:

    collection.insert(json.loads(data))

其中数据例如:

    {"created_at":"Tue Dec 03 23:07:53 +0000 2013","id":408009726509596672,"id_str":"408009726509596672","text":"this is some text"}

如何以编程方式将所有字符串“created_at”日期转换为集合中的日期时间对象?

从数据库中“找到”推文并遍历它们的最佳方式是什么?

我一直在尝试这样的事情:

import pymongo, datetime

from pymongo import MongoClient

client = MongoClient()

#access database
db = client.tweets

#access collection
collection = db.collection_name


tweets = collection.find({}) #just get all of the tweets in the collection.

for tweet in tweets:
    print tweet #how do I update the created_at field for each tweet in the collection  here?

编辑: 我最终使用了 Jose 和 Xcorat 的混合答案。

对于那些希望纯粹在 Python 中执行此操作的人(继续我上面的代码),这就是我所做的:

for tweet in tweets:
    thedate = tweet[u'created_at'] #in my case I was storing the date as unicode not datetime.
    if(type( thedate ) == unicode):
        proper_date = datetime.datetime.strptime(thedate,'%a %b %d %H:%M:%S +0000 %Y')
        pointer = tweet[u'_id']
        collection.update({'_id': pointer}, {'$set': {'created_at': proper_date}})
        print('updated created_at from unicode to datetime\n')
    else:
        print('skipping as is already datetime...\n')

【问题讨论】:

    标签: python json mongodb datetime twitter


    【解决方案1】:

    为什么不在 Mongo 上写一个脚本来做呢?

    在 Mongo shell 中,类似

    db.collection.find().forEach(function (tweet){
        db.collection.update({_id: tweet._id}, 
                             {$set: {created_at: new Date(tweet.created_at)}});
    });
    

    只需将所有内容压缩成一行,然后在 mongo shell 中剪切/粘贴,就完成了。

    【讨论】:

      【解决方案2】:

      嗯,要将这些字符串转换为日期时间,您可以使用 strptime 函数,如下所示:

      import datetime
      s = "Tue Dec 03 23:07:53 +0000 2013"
      proper_date = datetime.datetime.strptime(s,'%a %b %d %H:%M:%S +0000 %Y')
      

      现在,您必须遍历集合中的所有推文,获取旧日期并使用新日期进行更新。我对 MongoDB 了解不多,但我猜你可以使用循环,或者进行某种大规模更新。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-02
        • 1970-01-01
        • 2020-09-08
        • 2021-04-16
        • 2010-12-06
        • 1970-01-01
        相关资源
        最近更新 更多