将时间和日期分成不同的列(格式=2019-05-26T13:50:56.335288Z)

Separating time and date into different columns (format=2019-05-26T13:50:56.335288Z)

在我的数据中,时间和日期存储在列 'cord'(class=因子)中。我想将日期和时间分成两列。

数据如下所示:

1 2019-05-26T13:50:56.335288Z
2 2019-05-26T17:55:45.348073Z
3 2019-05-26T18:12:00.882572Z 
4 2019-05-26T18:26:49.577310Z 

我已经使用以下方法成功提取了日期:cord$Date <- as.POSIXct(cord$Time)

然而,我无法找到以“H:M:S”格式提取时间的方法。

dput(head(cord$Time)) returns 的输出一长串时间戳:“2020-04-02T13:34:07.746777Z”、“2020-04-02T13:41:11.095014Z”、 “2020-04-02T14:08:05.508818Z”、“2020-04-02T14:17:10.337101Z”等等...

我通常使用 lubridatedata.table 来完成约会和操作工作。这适用于我将您的一些原始日期复制为字符串

library(lubridate)
library(data.table)

x <- c("2019-05-26T13:50:56.335288Z", "2019-05-26T17:55:45.348073Z")
# lubridate to parse to date time
y <- parse_date_time(x, "ymd HMS")

# data.table to split in to dates and time
split_y <- tstrsplit(y, " ")
dt <- as.data.table(split_y)
setnames(dt, "Date", "Time")
dt[]

# if you use data.frames instead
df <- as.data.frame(dt)
df

摘录H:M:S

library(lubridate)
format(as_datetime(cord$Time), "%H:%M:%S")
#> [1] "13:50:56" "17:55:45" "18:12:00" "18:26:49"

如果你也需要毫秒:

format(as_datetime(cord$Time), "%H:%M:%OS6")
#> [1] "13:50:56.335288" "17:55:45.348073" "18:12:00.882572" "18:26:49.577310"

电线在哪里:

cord <- read.table(text = "  Time
1 2019-05-26T13:50:56.335288Z
2 2019-05-26T17:55:45.348073Z
3 2019-05-26T18:12:00.882572Z 
4 2019-05-26T18:26:49.577310Z ", header = TRUE)