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

如何从Google Calendar API下载数据至R语言环境

用R通过Google Calendar API获取数据并转为DataFrame的示例代码

准备工作

  • 确保已在Google Cloud Console启用Google Calendar API
  • 拥有有效的API密钥(仅用于公开日历)或OAuth服务账号密钥/交互式OAuth权限(用于私人日历)

步骤1:安装并加载依赖包

# 首次运行安装所需包
install.packages(c("googleAuthR", "dplyr", "purrr", "tidyr"))

# 加载包
library(googleAuthR)
library(dplyr)
library(purrr)
library(tidyr)

步骤2:配置认证

根据你的使用场景选择一种认证方式:

场景1:访问私人日历(OAuth认证)

# 方式A:使用服务账号密钥文件(适合自动化脚本)
gar_auth_service(json_file = "你的服务账号密钥文件路径.json")

# 方式B:交互式OAuth认证(适合个人手动操作)
gar_auth()

场景2:访问公开日历(API密钥)

gar_set_api_key("你的Google API密钥")

步骤3:获取目标日历ID

先获取你的日历列表,从中找到需要访问的日历ID:

# 调用API获取日历列表
calendar_list <- gar_api_generator(
  "https://www.googleapis.com/calendar/v3/users/me/calendarList",
  "GET",
  pars_args = list(maxResults = 10)
)()

# 将日历信息转为DataFrame
calendar_df <- as.data.frame(calendar_list$items) %>%
  select(id, summary)

# 打印日历ID和名称
print(calendar_df)

步骤4:获取日历事件并转为DataFrame

定义函数批量提取事件,并整理成标准DataFrame:

# 自定义函数:获取指定日历的事件
get_calendar_events <- function(calendar_id, start_time, end_time) {
  # 调用Calendar API获取事件
  events_response <- gar_api_generator(
    "https://www.googleapis.com/calendar/v3/calendars/{calendarId}/events",
    "GET",
    path_args = list(calendarId = calendar_id),
    pars_args = list(
      timeMin = start_time,
      timeMax = end_time,
      singleEvents = TRUE, # 展开重复事件
      orderBy = "startTime" # 按开始时间排序
    )
  )()
  
  # 解析响应并整理为DataFrame
  events_df <- map_dfr(events_response$items, function(event) {
    # 处理开始/结束时间(兼容纯日期和日期时间格式)
    start_val <- event$start$dateTime %||% event$start$date
    end_val <- event$end$dateTime %||% event$end$date
    
    tibble(
      event_id = event$id,
      title = event$summary,
      start_time = start_val,
      end_time = end_val,
      description = event$description %||% NA_character_,
      location = event$location %||% NA_character_
    )
  })
  
  return(events_df)
}

# 使用示例:获取2024年全年的事件
target_calendar_id <- "替换为你的日历ID" # 从calendar_df中获取
events_df <- get_calendar_events(
  calendar_id = target_calendar_id,
  start_time = "2024-01-01T00:00:00Z",
  end_time = "2024-12-31T23:59:59Z"
)

# 查看最终结果
print(events_df)

关键注意事项

  • 若使用服务账号访问私人日历,需在Google Calendar中将日历共享给服务账号的邮箱地址
  • timeMin和timeMax参数需遵循RFC3339格式(如示例中的YYYY-MM-DDTHH:MM:SSZ)
  • 若事件数量较多,需处理分页(可通过pageToken参数实现)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 00:04:02