如何将字符串日期时间列转换为 R 中的日期时间列?

How can I convert a string datetime column to a datetime column in R?

这应该很简单,但我找不到正确的语法。我有一个名为 data 的数据框,它有点像这样:

Id     timestamp 
A9     2020-08-10 09:05:01.000000
B9     2020-08-10 09:04:18.000000
G1     2020-04-15 11:05:08.000000
D2     2020-01-18 19:04:05.000000
F8     2020-02-12 08:04:08.000000

但是,列时间戳是一个字符串。如何转换为日期时间列?

我试过这个:

data$timestamp_new <- as.Date(data$timestamp,format="%Y-%m-%dT%H:%M:%OS")

还有这个:

data$timestamp_new <- as.POSIXct(data$timestamp,format="%Y-%m-%dT%H:%M:%OS")

两者都返回

我们可以直接使用%T

as.Date(data$timestamp, "%Y-%m-%d %T")
#[1] "2020-08-10" "2020-08-10" "2020-04-15" "2020-01-18" "2020-02-12"

数据

data <- structure(list(Id = c("A9", "B9", "G1", "D2", "F8"), timestamp = c("2020-08-10 09:05:01.000000", 
"2020-08-10 09:04:18.000000", "2020-04-15 11:05:08.000000", "2020-01-18 19:04:05.000000", 
"2020-02-12 08:04:08.000000")), class = "data.frame", row.names = c(NA, 
-5L))

您可以使用 ymd_hms 来自 lubridate

lubridate::ymd_hms(data$timestamp)
#[1] "2020-08-10 09:05:01 UTC" "2020-08-10 09:04:18 UTC" "2020-04-15 11:05:08 UTC"
#[4] "2020-01-18 19:04:05 UTC" "2020-02-12 08:04:08 UTC"

如果您只对日期感兴趣,可以将 as.Date 换行到上面的结果。