Answer the question
In order to leave comments, you need to log in
How to pull #hashtag data from the Twitter API in a specific time period in Python?
Friends, I use Ipython, I drag API through Tweepy. The other day there was a need to find out data about a hashtag a year ago, I surfed the Internet, found codes, but not working ones. As a result, I came across this
import tweepy
from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
import json
import datetime
#Use your keys
consumer_key = '...'
consumer_secret = '...'
access_token = '...'
access_secret = '...'
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)
def date_range(start,end):
current = start
while (end - current).days >= 0:
yield current
current = current + datetime.timedelta(seconds=1)
class TweetListener(StreamListener):
def on_status(self, status):
#api = tweepy.API(auth_handler=auth)
#status.created_at += timedelta(hours=900)
startDate = datetime.datetime(2013, 06, 30)
stopDate = datetime.datetime(2013, 10, 30)
for date in date_range(startDate,stopDate):
status.created_at = date
print "tweet " + str(status.created_at) +"\n"
print status.text + "\n"
# You can dump your tweets into Json File, or load it to your database
stream = Stream(auth, TweetListener(), secure=True, )
t = u"#Syria" # You can use different hashtags
stream.filter(track=[t])
Answer the question
In order to leave comments, you need to log in
At least, because this is code for version 2 of python, and you are running it on version 3.4. Also, in the traceback it is indicated
startDate=datetime.datetime('2015-06-30')
And in 3.4, the input of the datetime function must be given numbers separated by a comma. And it's better to put all this code in a .py file and run the file itself, and not through ipython. Yes, and the error indicates that the argument must be a number, not a string.
Here is an option for version 3 that works for me:
import datetime
startdate = datetime.datetime(2013, 10, 6)
enddate = datetime.datetime(2013, 11, 6)
def date_range(start,end):
current = start
while (end - current).days >= 0:
yield current
current = current + datetime.timedelta(seconds=1)
for date in date_range(startdate, enddate):
created_at = date
print("tweet " + str(created_at) +"\n")
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question