如何将日期和时间分为两列

时间:2019-05-05 13:14:17

标签: r date time

我需要拆分10/4/2018 19:21 并尝试过

AccidentsMp$Hours <- format(as.POSIXct(AccidentsMp$Job.Date, "%Y-%m-%d %H:%M:%S", tz = ""), format = "%H:%M")

AccidentsMp$Dates <- format(as.Date(AccidentsMp$Job.Date,"%Y-%m-%d"), format = "%d/%m/%Y")

如何将上述日期和时间分为两列?数据现在为factor类。

3 个答案:

答案 0 :(得分:1)

如果您的数据遵循与所示相同的格式,我们可以仅使用基数R进行以下操作

df$datetime <- as.POSIXct(df$Job.Date, format = "%d/%m/%Y %H:%M")
transform(df, time = format(datetime, "%T"), date = format(datetime, "%d/%m/%Y"))

#        Job.Date            datetime     time       date
#1 10/4/2018 19:21 2018-04-10 19:21:00 19:21:00 10/04/2018
#2 10/4/2018 19:22 2018-04-10 19:22:00 19:22:00 10/04/2018
#3 10/4/2018 19:23 2018-04-10 19:23:00 19:23:00 10/04/2018

如果不需要,您可以稍后删除datetime列。

数据

df <- data.frame(Job.Date = c("10/4/2018 19:21", "10/4/2018 19:22",
                              "10/4/2018 19:23"))

答案 1 :(得分:1)

如果需要用困难的方式做到这一点:

text<-"10/4/2018 19:21"
res<-strsplit(text," ")
df$Date<-res[[1]][1]
df$Time<-res[[1]][2]
#install.packages("lubridate")
df$Date<-lubridate::mdy(df$Date)
df$Time<-lubridate::hm(df$Time)

您无需使用任何软件包即可获取时间和日期:

df$Time<-format(strptime(res[[1]][2],"%H:%M",tz=""),"%H:%M") #cleaner output
df$Date<- as.Date(res[[1]][1],"%m/%d/%Y")

使用lubridate 的结果:

 month item sales       Date       Time
1     1    A    10 2018-10-04 19H 21M 0S
2     2    b    20 2018-10-04 19H 21M 0S
3     2    c     5 2018-10-04 19H 21M 0S
4     3    a     3 2018-10-04 19H 21M 0S

数据

df<-structure(list(month = c(1, 2, 2, 3), item = structure(c(2L, 
3L, 4L, 1L), .Label = c("a", "A", "b", "c"), class = "factor"), 
    Time = new("Period", .Data = c(0, 0, 0, 0), year = c(0, 0, 
    0, 0), month = c(0, 0, 0, 0), day = c(0, 0, 0, 0), hour = c(19, 
    19, 19, 19), minute = c(21, 21, 21, 21))), class = "data.frame", row.names = c(NA, 
-4L))

答案 2 :(得分:1)

这里是tidyverse

的一个选项
library(tidyverse)
library(lubridate)
df %>% 
  mutate(Job.Date = dmy_hm(Job.Date)) %>% 
  separate(Job.Date, into = c('date', 'time'), sep=' ', remove = FALSE)
#           Job.Date       date     time
#1 2018-04-10 19:21:00 2018-04-10 19:21:00
#2 2018-04-10 19:22:00 2018-04-10 19:22:00
#3 2018-04-10 19:23:00 2018-04-10 19:23:00

或使用base R

read.table(text = as.character(df$Job.Date), header = FALSE,
     col.names = c("date", "time"))

数据

df <- structure(list(Job.Date = structure(1:3, .Label = c("10/4/2018 19:21", 
"10/4/2018 19:22", "10/4/2018 19:23"), class = "factor")), 
 class = "data.frame", row.names = c(NA, -3L))