Search code examples
rposixdifftime

Difftime function always give me 0


I am pretty new to R and programming... So I had a couples of dates in my dataset with this format "%Y-%m-%d %H:%M:%OS" as stored as chr, so I used this to convert it to the format i want.

 x <- as.POSIXct(data$data , format = "%Y-%m-%d %H:%M:%OS")
data$data <- format(x, "%d/%m/%Y %H:%M")
 x <- as.POSIXct(data$data1 , format = "%Y-%m-%d %H:%M:%OS")
    data$data1 <- format(x, "%d/%m/%Y %H:%M")

Now I want the time diference between both times, so I use:

x <- difftime(data$data, data$data1 ,units = "mins")

And When I try to view x it gives me 0. In adition my data$data and data$data1 are still chr, is this normal? Am I missing any step?


Solution

  • First convert them as.POSIXct, then use format to change them:

    data$data <- as.POSIXct(data$data , format = "%Y-%m-%d %H:%M:%OS")
    data$data1 <- as.POSIXct(data$data1 , format = "%Y-%m-%d %H:%M:%OS")
    
    data$data <- format(data$data, "%d/%m/%Y %H:%M")
    data$data1 <- format(data$data1, "%d/%m/%Y %H:%M")