[R] datetime and date

Jim Lemon jim at bitwrit.com.au
Mon Feb 3 03:08:45 CET 2014

On 02/03/2014 12:53 PM, Yolande Tra wrote:
> Hi,
> I have the following issue. The dataframe  df has a column (Date1) supposed
> to be a date but read as a factor. There are two types of values in the
> same column Date1
> Type 1 are datetime like "5/23/2008 0:00:00"
> Type 2 have no time like "1/10/13".
> When I apply the following to the date column
> df$Date1<-as.POSIXct(as.character(df$Date1, format = "%d/%m/%Y"))
> For type 1 I got the expected result: "2008-05-23"
> For type 2 I got NA.
> I have searched but could not solve it. Please help.
Hi Yolande,
Try this:

# first get the dates with times
  as.POSIXct(as.character(df$Date1, format = "%m/%d/%Y %H:%M:%S"))
# then fill in the ones without times
df$Date1[nchar(df$Date1) < 10]<-
  as.POSIXct(as.character(df$Date1, format = "%m/%d/%y"))

Notice that I think you got the month/day order wrong, if your first 
type is correct.


More information about the R-help mailing list