Hugh Perkins
Hugh Perkins

Reputation: 8572

How to find the difference between two dates in hours in R?

At the extreme risk of being modded down for asking "obvious" questions, how do I find the difference between two dates in hours in R?

> ISOdate(2004,1,6) - ISOdate(2004,1,1)
Time difference of 5 days
> as.POSIXlt(ISOdate(2004,1,6) - ISOdate(2004,1,1))
Error in as.POSIXlt.default(ISOdate(2004, 1, 6) - ISOdate(2004, 1, 1)) : 
  do not know how to convert 'ISOdate(2004, 1, 6) - ISOdate(2004, 1, 1)' to class "POSIXlt"
 > (ISOdate(2004,1,6) - ISOdate(2004,1,1))$year
Error in (ISOdate(2004, 1, 6) - ISOdate(2004, 1, 1))$year : 
  $ operator is invalid for atomic vectors
> (ISOdate(2004,1,6) - ISOdate(2004,1,1))$mon
Error in (ISOdate(2004, 1, 6) - ISOdate(2004, 1, 1))$mon : 
  $ operator is invalid for atomic vectors

Upvotes: 4

Views: 13930

Answers (1)

Andrie
Andrie

Reputation: 179398

Use the function difftime, with the argument units="hours":

x <- c(ISOdate(2004,1,6), ISOdate(2004,1,1))
difftime(x[1], x[2], units="hours")
Time difference of 120 hours

How did I know where to look?

Well, start by looking at the structure of the object you get when you subtract two times:

str(x[1] - x[2])
Class 'difftime'  atomic [1:1] 5
  ..- attr(*, "units")= chr "days"

So now you know you are dealing with a class of difftime. From here it's easy to find help: See ?difftime

Upvotes: 16

Related Questions