[r] How do I convert a factor into date format?

I imported a CSV file with dates from a SQL query, but the dates are really date-time values and R doesn't seem to recognize them as dates:

> mydate
[1] 1/15/2006 0:00:00
2373 Levels: 1/1/2006 0:00:00 1/1/2007 0:00:00 1/1/2008 0:00:00 ... 9/9/2012 0:00:00
> class(mydate)
[1] "factor"
> as.Date(mydate)
Error in charToDate(x) : 
  character string is not in a standard unambiguous format

How do I convert mydate to date format? (I don't need to include the time portion.)

This question is related to r

The answer is


You can try lubridate package which makes life much easier

library(lubridate)

mdy_hms(mydate)

The above will change the date format to POSIXct

A sample working example:

> data <- "1/15/2006 01:15:00"
> library(lubridate)
> mydate <- mdy_hms(data)
> mydate
[1] "2006-01-15 01:15:00 UTC"
> class(mydate)
[1] "POSIXct" "POSIXt" 

For case with factor use as.character

data <- factor("1/15/2006 01:15:00")
library(lubridate)
mydate <- mdy_hms(as.character(data))

Take a look at the formats in ?strptime

R> foo <-  factor("1/15/2006 0:00:00")
R> foo <- as.Date(foo, format = "%m/%d/%Y %H:%M:%S")                                           
R> foo                                                                                       
 [1] "2006-01-15"                                                                             
R> class(foo)                                                                                
 [1] "Date"  

Note that this will work even if foo starts out as a character. It will also work if using other date formats (as.POSIXlt, as.POSIXct).