Calculate difference between dates in Hours in R

7

I have two dates in date and time format.

Data1 <- 20/01/2018 20:33:58
Data2 <- 21/01/2018 20:23:48

The difference in hours is 23:49:50 . How is the calculation of this difference in R?

In addition, I need to know if this difference above is more or less than 24 hours. How do I do this check?

    
asked by anonymous 07.03.2018 / 15:49

1 answer

7

You can use the difftime function, but remember that the dates must be in Date-Time or Date .

To transform character into Date-Time :

  Data1 <- "20/01/2018 20:33:58"
  Data2 <- "21/01/2018 20:23:48"

  # Converter
  Data1 <- strptime(Data1, "%d/%m/%Y %H:%M:%S")
  Data2 <- strptime(Data2, "%d/%m/%Y %H:%M:%S")

  class(Data1)
  > [1] "POSIXct" "POSIXt"

Calculate the difference:

  difer <- difftime(Data2, Data1, units = 'hour')
  > Time difference of 23.99722 hours

I do not know what context you want to use, but you can use if else to know if the difference is greater or less than 24h.

  if(difer[[1]] > 24) {
    "fazer algo se mais que 24"
  }else{
    "fazer algo se menos que 24h"
  }
    
07.03.2018 / 16:24