Search code examples
rdatestrptime

Date to another format: issue with the time in R


I have this kind of dates:

dates <- c("2018-09-01 00:48:30","2018-09-01 01:34:20", "2018-09-01 01:56:28", "2018-09-01 00:06:31", "2018-09-01 01:24:30", "2018-09-01 00:54:31") 

That are in chr format. I would like to get dd/mm/yy hh:mm:ss. So I tried

dates_2  <-as.character(as.Date(dates, "%Y-%m-%d %H:%M:%S"), "%d/%m/%Y %H:%M:%S") 

But the result is

c("01/09/2018 00:00:00", "01/09/2018 00:00:00", "01/09/2018 00:00:00", 
"01/09/2018 00:00:00", "01/09/2018 00:00:00", "01/09/2018 00:00:00"

Where the hh:mm:ss did not go through... Any ideas why?

Thanks!


Solution

  • Base R's date type does not include time. One option is to use strptime to first convert your text date times to POSIXlt, using an appropriate format mask. Then, convert back to an output string using strftime, again using the mask you want.

    x <- strptime(dates, format="%Y-%m-%d %H:%M:%S")
    output <- strftime(x, format="%d/%m/%Y %H:%M:%S")
    
    [1] "01/09/2018 00:48:30" "01/09/2018 01:34:20" "01/09/2018 01:56:28"
    [4] "01/09/2018 00:06:31" "01/09/2018 01:24:30" "01/09/2018 00:54:31"