datetime and date
On 02/03/2014 01:08 PM, Jim Lemon wrote:
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 df$Date1<- 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. Jim
Hi Yolande, Oops, major error. Change the name of the variable or you won't get the second lot of dates: # first get the dates with times df$Date2<- as.POSIXct(as.character(df$Date1, format = "%m/%d/%Y %H:%M:%S")) # then fill in the ones without times df$Date2[nchar(df$Date1) < 10]<- as.POSIXct(as.character(df$Date1, format = "%m/%d/%y")) Jim