tweepy 获取两个日期之间的推文 [英] tweepy get tweets between two dates

查看:95
本文介绍了tweepy 获取两个日期之间的推文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Python 中有以下代码:

I have the following code in Python:

import tweepy

consumer_key = "..."
consumer_secret = "..."

access_token = "..."
access_token_secret = "..."

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)

start_date = datetime.datetime(2018, 1, 19, 12, 00, 00)
end_date = datetime.datetime(2018, 1, 19, 13, 00, 00)

api = tweepy.API(auth)

for tweet in tweepy.Cursor(api.user_timeline, screen_name="@IBM", since=start_date, until=end_date).items():
    print("ID TWEET: " + str(tweet.id))

有没有办法通过用 tweepy 修改光标来获取 start_dateend_date 之间的推文?

Is there a way to get tweets between start_date and end_date, by modifying the cursor with tweepy?

我已经尝试使用 since=until= 参数,但它们没有奏效.

I have already tried to use the since= and until= parameters, but they have not worked.

提前致谢.

推荐答案

首先,Twitter API 不允许按时间搜索.简单地说,您可以做的是在 Python 中获取推文并随后查看它们的时间戳,但这是非常低效的.

First of all the Twitter API does not allow to search by time. Trivially, what you can do is fetching tweets and looking at their timestamps afterwards in Python, but that is highly inefficient.

您可以通过以下代码片段来做到这一点.

You can do that by the following code snippet.

consumerKey = "CONSUMER_KEY"
consumerSecret = "CONSUMER_SECRET"
accessToken = "ACCESS_TOKEN"
accessTokenSecret = "ACCESS_TOKEN_SECRET"

auth = tweepy.OAuthHandler(consumerKey, consumerSecret)
auth.set_access_token(accessToken, accessTokenSecret)

api = tweepy.API(auth)

username = sys.argv[1]
startDate = datetime.datetime(2011, 6, 1, 0, 0, 0)
endDate =   datetime.datetime(2012, 1, 1, 0, 0, 0)

tweets = []
tmpTweets = api.user_timeline(username)
for tweet in tmpTweets:
    if tweet.created_at < endDate and tweet.created_at > startDate:
        tweets.append(tweet)

while (tmpTweets[-1].created_at > startDate):
    tmpTweets = api.user_timeline(username, max_id = tmpTweets[-1].id)
    for tweet in tmpTweets:
        if tweet.created_at < endDate and tweet.created_at > startDate:
            tweets.append(tweet)

虽然效率极低.它有效,可以帮助我创建自己的机器人.

Although highly inefficient. It works, can helped me in creating my own bot.

这篇关于tweepy 获取两个日期之间的推文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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