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

在R中能否将时间格式化为yyyy-mm-dd hh:mm:ss+00?求改代码方案

解决方案

完全可行,你只需要将Time_sp列从日期时间对象转换为带指定后缀的字符串格式即可。这里提供两种实现方式:

方式一:分组后转换格式

在数据汇总完成后,通过mutate()配合strftime()函数将日期时间格式化为目标字符串:

abc <- merged %>%
  select(any_of(cn)) %>%
  as_tibble() %>%
  group_by(Time_sp = lubridate::floor_date(`Date/Time`, "5 mins")) %>% 
  summarise(across(where(is.numeric), ~ if(mean(is.na(.x)) > 0.5) NA else mean(.x, na.rm = TRUE))) %>%
  # 将日期时间格式化为带+00后缀的字符串
  mutate(Time_sp = strftime(Time_sp, "%Y-%m-%d %H:%M:%S+00"))

write.csv(abc, paste0(dirlist[idx],"_mean.csv"), row.names = FALSE)

方式二:分组时直接生成格式化字符串

如果你希望在分组阶段就直接使用格式化后的字符串作为分组键,也可以直接在group_by()中完成格式转换:

abc <- merged %>%
  select(any_of(cn)) %>%
  as_tibble() %>%
  # 直接生成带+00后缀的字符串作为分组键
  group_by(Time_sp = strftime(lubridate::floor_date(`Date/Time`, "5 mins"), "%Y-%m-%d %H:%M:%S+00")) %>% 
  summarise(across(where(is.numeric), ~ if(mean(is.na(.x)) > 0.5) NA else mean(.x, na.rm = TRUE)))

write.csv(abc, paste0(dirlist[idx],"_mean.csv"), row.names = FALSE)

说明

  • strftime()函数可以将日期时间对象按照指定格式转换成字符串,%Y-%m-%d %H:%M:%S对应你需要的基础日期时间格式,末尾直接拼接+00即可得到目标格式。
  • 两种方式的分组逻辑完全一致,最终输出的CSV文件中Time_sp列都会呈现为yyyy-mm-dd hh:mm:ss+00格式。

内容的提问来源于stack exchange,提问作者Alexia k Boston

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 08:43:12