Twitter API v2:当参数有 start_time、end_time 时响应失败
Posted
技术标签:
【中文标题】Twitter API v2:当参数有 start_time、end_time 时响应失败【英文标题】:Twitter API v2: response failing when params has start_time, end_time 【发布时间】:2021-06-18 01:32:06 【问题描述】:一直在玩 Twitter API。事情进展顺利,直到我为搜索添加了开始和结束时间以及粒度。 根据 Twitter api docs,我相当有信心字符串值是正确的,并且 正确添加到参数。 但是我在参数上做错了什么,有人可以帮我吗?
有效的代码,IE 导致 200 响应和推文:
keywords = 'telsa'
api, query = 'https://api.twitter.com/2', '/tweets/search/recent'
request = f'apiquery'
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)
不起作用的代码:400 响应:添加 start_time、end_time、粒度
<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>
..以及最后打印的参数:
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'
twitter API docs 显示 start_time、end_time 示例值。它们的格式相同。 最近发布的使用 API v2 的教程以相同的方式附加了新参数。 添加 3 个新时间变量的任意组合会导致 400 响应。 Windows 10、64 如果重要的话
【问题讨论】:
【参考方案1】:我想你得到this 错误。
Twitter API 使用 UTC 时间,可能早于或晚于您的本地时间。
尝试从这里改变
# 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)
到这里
# 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)
【讨论】:
【参考方案2】:不确定这是否有帮助,但我收到了对以下 URL(我也在使用 Bearer 令牌)的良好响应,其中传递了 start_time、end_time 和粒度:
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))
收到的回复:200
【讨论】:
以上是关于Twitter API v2:当参数有 start_time、end_time 时响应失败的主要内容,如果未能解决你的问题,请参考以下文章
Twitter4j v2.2.6 带有地理定位的流式 API
Tweepy [ Twitter API v2 ] 无法上传照片/媒体 [重复]
使用 tweepy 和 Twitter API V2 发布推文