4

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
Charles
  • 50,943
  • 13
  • 104
  • 142
Hugh Perkins
  • 7,975
  • 7
  • 63
  • 71
  • 2
    thanks for the drive-by down-vote. A document explaining how to do this might be useful. Everything I've seen points to strptime, which involves strings, and strings are highly sensitive to regional settings for dates. – Hugh Perkins Oct 19 '12 at 15:07
  • 3
    `?ISOdate` tells you to read `?DateTimeClasses`, which tells you that "Subtraction of two date-time objects is equivalent to using `difftime`." Please read the documentation before asking "obvious" questions. – Joshua Ulrich Oct 19 '12 at 15:14

1 Answers1

16

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

Andrie
  • 176,377
  • 47
  • 447
  • 496
  • Yay! Thanks! Note that it seems to require "as.numeric" to be added in order to get the actual number. – Hugh Perkins Oct 19 '12 at 15:11
  • 3
    @HughPerkins Again I think you are not noting how an object is actually stored. Do `tmp <- difftime(x[1], x[2], units="hours")` then `unclass(tmp)` notice that it is a numeric vector of length one. It is the print method and the use of the attribute `"units"` that gives it a character flavour. you don't need to convert it to numeric to use it as it is already numeric; `tmp + 1` for example. The `as.numeric()` you mention is only clearing out the class and `"units"` attribute. – Gavin Simpson Oct 19 '12 at 15:39