Been playing with the Twitter API. Things were going well until I added start and end times, and granularity to my searches.
I’m fairly confident the string values are correct, as per Twitter api docs, and
added correctly to params.
However I’m doing something wrong with params, could someone help me please.
Code that works, IE results in a 200 response, and tweets:
keywords = 'telsa'
api, query = 'https://api.twitter.com/2', '/tweets/search/recent'
request = f'{api}{query}'
params = {'query': keywords,
'tweet.fields': 'created_at,lang', # no space before lang
'max_results': '10'}
header = {'authorization':f'Bearer {bearer_token}'}
response = requests.get(request, headers=header, params=params)
if response: # boolean True if response is 200,
print(response.response.json())
else:
print(response)
print(params)
Code that does not work: a 400 response: Adding start_time, end_time, granularity
<snip>
header = {'authorization':f'Bearer {bearer_token}'}
**************** NEW CODE **************************
# Get datetime for now and 7 days ago, correctly formatted for Twitter API
dtformat = '%Y-%m-%dT%H:%M:%SZ'
from datetime import datetime, timedelta
time = datetime.now()
start_time = time - timedelta(days=7)
# convert to strings
start_time, end_time = start_time.strftime(dtformat), time.strftime(dtformat)
# Add new parameters to params dict
params['start_time'] = start_time
params['end_time'] = end_time
params['granularity'] = 'HOUR'
****************************************************
response = requests.get(request, headers=header, params=params)
<snip>
..and the params as printed at the end:
params: {'query': 'telsa', 'tweet.fields': 'created_at,lang', 'max_results': '10', 'start_time': '2021-03-14T14:14:44Z', 'end_time': '2021-03-21T14:14:44Z', 'granularity': 'HOUR'}
The twitter API docs show start_time, end_time example values. They are the same format.
The recently published tutorial using API v2 appends the new parameters in the same way.
Adding any combination of the 3 new time variables results in a 400 response.
Windows 10, 64 if that matters
2
Answers
Not sure if this is helpful, but I received a good response for the following URL (I am also using Bearer token) with passed start_time, end_time and granularity:
Response received: 200
I suppose you are getting this error.
Twitter API uses time in UTC which may be ahead or behind your local time.
Try changing from this
to this