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

如何从mm/dd/yy hh:mm格式字符串提取年或年月并新建列

处理日期字符串并生成年份与中文年月列

数据准备

先把你的日期字符串向量加载到环境中:

starttime <- c("12/16/20 7:24", "6/21/21 13:20", "1/22/20 9:03", "1/07/20 17:19", 
"11/8/21 10:14", NA, NA, "10/26/21 7:19", "3/14/22 9:48", "5/12/22 13:29")
df <- data.frame(starttime = starttime)

步骤1:将字符型日期转换为日期时间格式

可以用lubridate包的mdy_hm()函数(适配月/日/年 时:分的格式),或者base R的as.POSIXct():

# 方法1:使用lubridate包
library(lubridate)
df$datetime <- mdy_hm(df$starttime)

# 方法2:base R实现
df$datetime <- as.POSIXct(df$starttime, format = "%m/%d/%y %H:%M")

步骤2:提取年份列

直接从转换后的日期时间中提取4位年份:

# lubridate方法
df$year <- year(df$datetime)

# base R方法
df$year <- format(df$datetime, "%Y")

步骤3:生成中文年月列

如果需要类似"2022年3月"的数字月份格式,直接格式化即可;如果需要中文月份(如"2022年三月"),可以自定义月份映射:

# 数字月份格式(如2022年03月)
df$year_month_num <- format(df$datetime, "%Y年%m月")

# 中文月份格式(如2022年三月)
month_cn <- c("一月", "二月", "三月", "四月", "五月", "六月", 
              "七月", "八月", "九月", "十月", "十一月", "十二月")
df$year_month_cn <- paste0(format(df$datetime, "%Y年"), month_cn[month(df$datetime)])

最终结果示例

处理后的df会包含原列、转换后的日期时间列、年份列,以及两种格式的中文年月列,NA值会自动保留为缺失值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 06:30:50