Search code examples
rlubridatedate-conversion

Convert Character to date


I have looked into some of the earlier answers but non of them solves my problem so here it is.

The data that I'm having is in the this format ( D-M-Y H:M) and this is a character variable.

This is the data set

23-03-2019 21:35
23-03-2019 21:36
23-03-2019 21:37
23-03-2019 21:44
23-03-2019 21:44
23-03-2019 21:44
23-03-2019 21:44

I have used this code but the results are showing NA's

data1 <- as.Date(data$InvoiceDate,  "%d/%m/%y %H:%M")

So please someone help me, I have gone through other similar answers to this question also but the results are the same.

Thanks


Solution

  • how about just overwriting that column as a date column:

    library(tidyverse)
    data <- data %>% mutate(InvoiceDate = dmy_hm(InvoiceDate)) #dmy_hm() converts to date
    #or if you really need a separate vector:
    data1 <- dmy_hm(data$InvoiceDate)
    

    you can read about dmy_hm()and similar functions in the tidyverse's sublibrary lubridate. I find it very useful.