How do I compare dates from Twitter data stored in MongoDB via PyMongo?

前端 未结 2 1885
旧时难觅i
旧时难觅i 2021-02-06 06:06

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

2条回答
  •  长情又很酷
    2021-02-06 07:10

    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')
    

    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)]))
    

提交回复
热议问题