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

在R语言中将Jan 1, 2000 12:00 AM格式字符串转日期时间的方法

R语言转换特定格式字符串为日期时间类型的实现方法

下面提供两种常用的可直接运行的实现方案:

方案1:基础包原生实现(无需额外安装依赖)

使用内置as.POSIXct()函数,手动匹配字符串格式即可:

# 若本地语言非英语,先运行下行修改时间识别语言,避免月份缩写识别失败
# Sys.setlocale("LC_TIME", "English")

datetime_str <- "Jan 1, 2000 12:01 AM"
# 格式符说明:%b=缩写月份 %d=日期 %Y=4位年份 %I=12小时制小时 %M=分钟 %p=AM/PM标识
datetime_res <- as.POSIXct(datetime_str, format = "%b %d, %Y %I:%M %p", tz = "UTC")

# 验证结果
print(datetime_res)
print(class(datetime_res))

tz参数为时区设置,可根据需求替换为你需要的时区,例如国内常用"Asia/Shanghai"。

方案2:使用lubridate包实现(语法更简洁)

lubridate是R生态专门处理时间数据的工具包,可自动匹配常用格式无需手动写格式符:

# 未安装包先运行下行安装
# install.packages("lubridate")
library(lubridate)

datetime_str <- "Jan 1, 2000 12:01 AM"
datetime_res <- mdy_hm(datetime_str, tz = "UTC")

# 验证结果
print(datetime_res)
print(class(datetime_res))

mdy_hm会自动识别「月-日-年 小时-分钟」结构,也默认兼容12小时制的AM/PM标识,不容易出现格式符写错的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 10:27:01