如何比较通过PyMongo存储在MongoDB中的Twitter数据中的日期? [英] How do I compare dates from Twitter data stored in MongoDB via PyMongo?

查看:96
本文介绍了如何比较通过PyMongo存储在MongoDB中的Twitter数据中的日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

存储在"created_at"字段中的日期是否通过PyMongo编组到Python日期时间对象,还是我必须用Python Date对象手动替换文本字符串?即

Are the dates stored in the 'created_at' fields marshaled to Python datetime objects via PyMongo, or do I have to manually replace the text strings with Python Date objects? i.e.

我如何将MongoDB中的属性从文本转换为日期类型?

我不得不用Python日期对象替换日期字符串似乎非常不自然,这就是为什么我要问这个问题.

It seems highly unnatural that I would have to replace the date strings with Python date objects, which is why I'm asking the question.

我想编写查询,以显示过去三天的推文.如果有一种巧妙的方法,请告诉我.谢谢!

I would like to write queries that display the tweets from the past three days. Please let me know if there is a slick way of doing this. Thanks!

推荐答案

您可以像这样将Twitter的created_at时间戳解析为Python日期时间:

you can parse Twitter's created_at timestamps to Python datetimes like so:

import datetime, pymongo
created_at = 'Mon Jun 8 10:51:32 +0000 2009' # Get this string from the Twitter API
dt = datetime.strptime(created_at, '%a %b %d %H:%M:%S +0000 %Y')

像这样将它们插入您的Mongo集合中:

and insert them into your Mongo collection like this:

connection = pymongo.Connection('mymongohostname.com')
connection.my_database.my_collection.insert({
    'created_at': dt,
    # ... other info about the tweet ....
}, safe=True)

最后,要在最近三天内获取推文,请先获取最新消息:

And finally, to get tweets within the last three days, newest first:

three_days_ago = datetime.datetime.utcnow() - datetime.timedelta(days=3)
tweets = list(connection.my_database.my_collection.find({
    'created_at': { '$gte': three_days_ago }
}).sort([('created_at', pymongo.DESCENDING)]))

这篇关于如何比较通过PyMongo存储在MongoDB中的Twitter数据中的日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆