user217763
user217763

Reputation: 31

How to split date and time into two columns

I need to split 10/4/2018 19:21 and have tried

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")

How can I split the above date and time it into two columns?The data is of class factor now.

Upvotes: 3

Views: 2095

Answers (3)

akrun
akrun

Reputation: 887118

Here is an option with 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

Or using base R

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

data

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))

Upvotes: 2

NelsonGon
NelsonGon

Reputation: 13319

If one needs to do it the hard way:

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)

You can get the time and date without using any packages as:

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

Result using 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

Data

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))

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388982

If your data follows the same format as shown we can do it as follows using only base 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

You can remove the datetime column later if not needed.

data

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

Upvotes: 1

Related Questions