Search code examples
rlubridatechron

lubridate hour doesn't handle chron times


I'm trying to extract the hour from a chron time in R. The help for lubridate::hour says the following:

Date-time must be a POSIXct, POSIXlt, Date, Period, chron, yearmon, yearqtr, zoo, zooreg, timeDate, xts, its, ti, jul, timeSeries, and fts objects.

But it doesn't seem to work:

library(chron)
library(lubridate)
hour(chron(times. = "01:02:03"))

gives the error

Error in as.POSIXlt.default(x, tz = tz(x)) : 
do not know how to convert 'x' to class “POSIXlt”

Is this a bug?

I know that it's possible to use chron::hours instead, which is preferable in most cases. But part of the appeal of lubridate is having one set of functions to work with all sorts of datetime data, and having to change hour to hours everywhere goes against this.


Solution

  • The problem is that tt below:

    library(chron)
    tt <- chron(times. = "01:02:03")
    class(tt)
    ## [1] "times"
    

    is not actually of class "chron". It is of class "times".

    1) It needs a date part too to be of class "chron" so this would work:

    library(lubridate)
    hour(chron(0, tt))
    ## [1] 1
    

    2) or:

    hour(as.chron(tt)) # as.chron always produces a chron object
    ## [1] 1
    

    3) An alternative not using lubridate is the following based on the fact that chron represents a day as 1 so 1 hour is 1/24:

    trunc(24 * as.numeric(tt))
    ## [1] 1