在 r 中将 YYYYMMDDHHMMSS 转换为日期和时间 class

Converting YYYYMMDDHHMMSS to a date and time class in r

我有包含以下格式的日期和时间的数据集:

datetime<- c(20210830102055, 20210830102312, 20210830102335)
cycle <- c(25, 30, 35)
df <- data.frame(datetime, cycle)
df 
     datetime cycle
1 2.021083e+13    25
2 2.021083e+13    30
3 2.021083e+13    35

我正在尝试将日期时间列转换为

datetime2<- c("2021-08-30 10:20:55", "2021-08-30 10:23:12", "2021-08-30 10:23:35")
df <- data.frame(datetime2, cycle)
df

            datetime2 cycle
1 2021-08-30 10:20:55    25
2 2021-08-30 10:23:12    30
3 2021-08-30 10:23:35    35

有什么有效的方法吗?

谢谢

您可以在 lubridate 包中使用 ymd_hms()

datetime<- c(20210830102055, 20210830102312, 20210830102335)
cycle <- c(25, 30, 35)
df <- data.frame(datetime = ymd_hms(datetime), cycle)

基地R:

data.frame(datetime2=as.POSIXct(as.character(df$datetime),
                                format="%Y%m%d%H%M%S"), 
           cycle)

输出:

            datetime2 cycle
1 2021-08-30 10:20:55    25
2 2021-08-30 10:23:12    30
3 2021-08-30 10:23:35    35

这里的关键是 as.POSIXctformat:

> as.POSIXct(as.character(df$datetime), format="%Y%m%d%H%M%S")
[1] "2021-08-30 10:20:55 CST" "2021-08-30 10:23:12 CST" "2021-08-30 10:23:35 CST"
>
datetime<- c(20210830102055, 20210830102312, 20210830102335)
cycle <- c(25, 30, 35)
df <- data.frame(datetime, cycle)

# METHOD 1
df$datetime <- as.POSIXct(as.character(df$datetime) , format = "%Y%m%d%H%M%S")

# METHOD 2

library(lubridate)
df$datetime <- ymd_hms(df$datetime)