tweepy get tweets between two dates

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.


I've just used until (optional operator) and it seems to work pretty well. I used it like this:

tweets = tw.Cursor(api.search,
                   q=search_words,
                   lang="en",
                   since=date_since,
                   until=date_until,
                   result_type="recent"
                   ).items(2)

Tags:

Python

Tweepy