adam.888
adam.888

Reputation: 7846

R splitting time date character to date and time

I have a character containing both time and date and I would like to split it into date and time. I tried:

datetime <-  as.character("12:00:00 03-May-2019")
date1 <- as.Date(datetime ,"%d/%m/%Y")
date1

time1 <- as.Date(datetime ,%H:%M:%S)
time1

but I just get NA returned.

Thank you for your help.

Upvotes: 0

Views: 176

Answers (2)

akrun
akrun

Reputation: 886938

The format should match the ones in the initial vector.

as.Date(datetime, "%H:%M:%S %d-%b-%Y")
#[1] "2019-05-03" "2018-05-03" "2017-05-03"

If the intention it to split by space " "

strsplit(datetime, "\\s+")

Or with read.table

df1 <- read.table(text = datetime, header = FALSE, col.names = c("time", "date"))
df1$date <- as.Date(df1$date, "%d-%b-%Y")
df1
#       time       date
#1 12:00:00 2019-05-03
#2 02:01:00 2018-05-03
#3 11:00:22 2017-05-03

Or with tidyverse

library(tidyverse)
tibble(datetime) %>% 
    separate(datetime, into = c('date', 'time'), sep=" ")  %>% 
    mutate(time = dmy(time))
# A tibble: 3 x 2
#  date     time      
#  <chr>    <date>    
#1 12:00:00 2019-05-03
#2 02:01:00 2018-05-03
#3 11:00:22 2017-05-03

data

datetime <-  c("12:00:00 03-May-2019",
           "02:01:00 03-May-2018",
           "11:00:22 03-May-2017")

Upvotes: 1

lefft
lefft

Reputation: 2105

Here is a function that will extract the date (as a Date object) and the time (as a character string). See this post and answers for some motivation for keeping the time as a character string.

extract_date_time <- function(dt){
  dt_split <- strsplit(dt, split=" ")
  lapply(dt_split, function(dts){
    list(date=as.Date(dts[2], '%d-%b-%Y'), time=dts[1])
  })
}

Example usage:

datetime <- as.character("12:00:00 03-May-2019")
extract_date_time(datetime)

You can also apply this function to a longer vector of strings like the one you originally have, like this:

datetimes <- c("12:00:00 03-May-2019",
               "02:01:00 03-May-2018",
               "11:00:22 03-May-2017")
extract_date_time(datetimes)

Upvotes: 1

Related Questions