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

R语言调用Reddit API获取指定时间评论的日期问题及修复

问题分析与修复方案

核心问题排查

你的问题大概率出在时间戳转换错误或API参数使用不当,以下是具体修复步骤:

1. 正确转换UTC秒级时间戳

Reddit API要求时间参数after和before必须是UTC时区的秒级Unix时间戳,常见错误是用本地时区转换或生成毫秒级时间戳。用lubridate包可以精准转换:

library(lubridate)

# 定义UTC时间范围(明确指定时区)
start_utc <- ymd_hms("2020-03-01 00:00:00", tz = "UTC")
end_utc <- ymd_hms("2020-03-02 00:00:00", tz = "UTC")

# 转换为秒级Unix时间戳(Reddit API要求)
start_ts <- as.integer(start_utc)
end_ts <- as.integer(end_utc)

2. 修正API请求参数

必须明确指定搜索类型为评论(type=comment),并使用Reddit API要求的时间参数名after(起始时间之后)和before(结束时间之前),同时确保认证正确。完整R代码示例:

library(httr)
library(lubridate)

# 替换为你的API认证信息
client_id <- "你的客户端ID"
client_secret <- "你的客户端密钥"
user_agent <- "你的应用名称/1.0 by 你的Reddit用户名"

# 获取访问令牌
auth_res <- POST(
  url = "https://www.reddit.com/api/v1/access_token",
  authenticate(client_id, client_secret),
  body = list(grant_type = "client_credentials"),
  user_agent(user_agent)
)
access_token <- content(auth_res)$access_token

# 时间戳转换(同步骤1)
start_utc <- ymd_hms("2020-03-01 00:00:00", tz = "UTC")
end_utc <- ymd_hms("2020-03-02 00:00:00", tz = "UTC")
start_ts <- as.integer(start_utc)
end_ts <- as.integer(end_utc)

# 发起评论搜索请求
search_res <- GET(
  url = "https://oauth.reddit.com/search",
  add_headers(Authorization = paste("Bearer", access_token)),
  query = list(
    q = "covid",               # 关键词
    type = "comment",          # 指定搜索评论(关键!)
    after = start_ts,          # 起始时间戳
    before = end_ts,           # 结束时间戳
    limit = 100,               # 请求数量
    sort = "new"               # 按时间排序,确保优先返回指定范围内的内容
  ),
  user_agent(user_agent)
)

# 解析返回的评论数据
comments <- content(search_res)$data$children

3. 验证返回结果的时间

提取评论的created_utc字段(UTC时间戳)并转换为日期,确认是否在指定范围内:

# 提取并格式化评论发布时间
comment_dates <- lapply(comments, function(comment) {
  as_datetime(comment$data$created_utc, tz = "UTC")
})

# 打印验证
print(comment_dates)

常见错误总结

  • 未指定UTC时区:直接转换本地时间会导致时间戳偏移,必须在ymd_hms中添加tz = "UTC"。
  • 毫秒级时间戳:部分工具生成的是毫秒级时间戳,Reddit API需要秒级,若误生成需除以1000。
  • 未指定type=comment:默认搜索帖子而非评论,导致返回内容的时间不符合预期。
  • 参数名错误:误用start/end等参数,Reddit API仅识别after和before作为时间范围参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 06:47:31