You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python获取指定时间区间内话题标签的推文数量

实现指定时间区间的推文数量统计

你可以通过以下方式实现目标:利用Tweepy的get_recent_tweets_count接口指定时间范围,结合小时粒度的计数结果筛选并累加目标区间的推文数量。

情况1:统计单个特定时间段(如某天00:00-23:00)

直接指定起始和结束时间,获取该时间段内的小时粒度数据后求和:

import tweepy
from datetime import datetime

query = "kitten"
# 替换为你的Bearer Token
client = tweepy.Client("<你的Bearer Token>")

# 设置目标时间范围(注意:Twitter API使用UTC时间)
start_time = datetime(2024, 5, 20, 0, 0, 0).isoformat() + "Z"
end_time = datetime(2024, 5, 20, 23, 0, 0).isoformat() + "Z"

# 获取小时粒度的推文计数
counts = client.get_recent_tweets_count(
    query=query,
    granularity='hours',
    start_time=start_time,
    end_time=end_time
)

# 计算目标区间的总推文数
total_tweets = sum(item["tweet_count"] for item in counts.data)
print(f"目标区间内的推文总数:{total_tweets}")

情况2:统计多天内每日固定时间段(如每天00:00-23:00)

循环遍历每一天,筛选每日目标小时区间的计数并累加:

import tweepy
from datetime import datetime, timedelta

query = "kitten"
client = tweepy.Client("<你的Bearer Token>")

# 定义要统计的天数(最多7天,受限于Twitter API的最近数据范围)
days_to_check = 7
# 目标小时区间:0点到22点对应凌晨12到晚上10点,若到晚上11点则改为range(0,24)
target_hours = range(0, 23)

total_count = 0

for day_offset in range(days_to_check):
    # 计算当天的UTC时间范围
    current_date = datetime.utcnow() - timedelta(days=day_offset + 1)
    day_start = current_date.replace(hour=0, minute=0, second=0, microsecond=0).isoformat() + "Z"
    day_end = current_date.replace(hour=23, minute=0, second=0, microsecond=0).isoformat() + "Z"
    
    # 获取当日小时粒度计数
    daily_counts = client.get_recent_tweets_count(
        query=query,
        granularity='hours',
        start_time=day_start,
        end_time=day_end
    )
    
    # 筛选目标小时的记录并累加当日数量
    daily_target_count = sum(
        item["tweet_count"] 
        for item in daily_counts.data 
        if int(item["start"][11:13]) in target_hours
    )
    total_count += daily_target_count
    print(f"{current_date.date()} 目标区间推文数:{daily_target_count}")

print(f"总计推文数:{total_count}")

关键注意事项

  • API限制:get_recent_tweets_count仅支持最近7天的数据,若需要更早的记录,需使用Twitter学术研究API。
  • 时区问题:所有时间参数需使用UTC格式,若需基于本地时间统计,需自行做时区转换。
  • 权限验证:确保你的Bearer Token已在Twitter开发者平台完成认证,且具备访问推文计数API的权限。

内容的提问来源于stack exchange,提问作者Hazza

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 15:18:13