Search code examples
rdatetimedataframeposixlt

Converting to datetime resulting in NA


I have a data frame with the following attributes and fields:

print(sapply(df1, typeof))

SurveyUserStart 
      "integer" 
print(df1)

 SurveyUserStart
1 2016-10-17 08:55:13
2 2016-04-24 14:31:12
3 2016-09-01 15:17:54
4 2016-07-20 11:26:56

I am trying to convert this column SurveyUserStart to datetime format. I have tried various methods below but I have always resulted in NA

df1$SurveyUserStart <- as.POSIXlt(as.character(df1$SurveyUserStart), format="%d/%m/%Y %H:%M")
df1$SurveyUserStart <- as.character(df1$SurveyUserStart, format="%m/%d/%Y  %H:%M:%S %p")

Solution

  • As already stated in the comments it is important in which order you give your format info to the function. If your date 2016-10-17 08:55:13 this means you have year-month-day hour:minute:second. If you want to transform to a date you have to give exactly this information yo the function in your case:

    as.POSIXct(x = as.character(df3$SurveyUserStart), format = "%Y-%m-%d %H:%M:%S")
    

    Please note that if you use the POSIXct function you also have to choose the right separator (in your case a -) between the different formats. If you use the package lubridate this is not needed anymore, however you still have to give the right order of your date object in the functionname (y=year, m=month, d=day, ...) which leads to the following function:

    ymd_hms(as.character(df3$SurveyUserStart))