skip to Main Content

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


  1. 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:

    url_link = "https://api.twitter.com/2/tweets/counts/recent?query=(%23ethereum OR %23eth)&granularity=day&start_time=2021-11-23T00:00:00Z&end_time=2021-11-23T23:59:59Z"
    
    def connect_to_endpoint(url, params):
         response = requests.get(url, auth=bearer_oauth, params=params)
         print(response.status_code)
         if response.status_code != 200:
               raise Exception(response.status_code, response.text)
         return response.json(
    def main():
         json_response = connect_to_endpoint(url_link, {})
         print(json.dumps(json_response, indent=4, sort_keys=True))
    

    Response received: 200

    Login or Signup to reply.
  2. 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

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

    to this

    # 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() gives you the local time whereas time = datetime.utcnow() 
    # gives the local time in UTC. Hence now() may be ahead or behind which gives the 
    # error
    
    time = datetime.utcnow()
    start_time = time - timedelta(days=7)
    
    # Subtracting 15 seconds because api needs end_time must be a minimum of 10 
    # seconds prior to the request time
    end_time = time - timedelta(seconds=15)
    
    # convert to strings
    start_time, end_time = start_time.strftime(dtformat), 
    end_time.strftime(dtformat)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search