【发布时间】: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