Calculate Time Difference in R

Asked

Viewed 1,340 times

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?

Also, I need to know if this difference above has more or less than 24 hours. How do I make this check?

1 answer

8


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

To transform character in 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 don’t know the context you want to use, but you can use one 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"
  }
  • My fields are in "Character" format and I am unable to make your suggestion. How to convert character to date and time(datetime)?

  • @Brunoavila edited the answer explaining how to convert from character for Date-Time.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.