Convert integer to ITime?
data.table, r
Solution
This works:
library(data.table)
DT = data.table(int = 37500L)
DT[, setattr(int, "class", "ITime")]
# int
# 1: 10:25:00
or
int = 37500L
setattr(int, "class", "ITime")
# "10:25:00"
Problem
I'm looking into using the new `data.table` date and time formats. Since `ITime` is stored as an integer under the hood (number of seconds since midnight): ``` x <- as.ITime( "10:25:00" ) i <- as.integer( x ) i [1] 37500 ``` It seems like it should be easy enough to convert an integer (assuming it's less than 24*60*60) to `ITime`, but I'm not finding how: ``` as.ITime( i ) Error in as.POSIXlt.numeric(x, ...) : 'origin' must be supplied as( i, "ITime" ) Error in as(i, "ITime") : no method or default for coercing “integer” to “ITime” ``` Providing an origin (which I gather gets passed to `as.POSIX...`) does help, but even then it only gives the right value (for my locale anyway) if you also specify `tz` as "UTC": ``` as.ITime( i, origin = "1970-01-01 00:00:00" ) [1] "20:25:00" as.ITime( i, origin = "1970-01-01 00:00:00", tz = "UTC" ) [1] "10:25:00" # note that the date seems necessary but irrelevant here as.ITime( i, origin = "2000-01-01 00:00:00", tz = "UTC" ) [1] "10:25:00" ``` What I'm talking about is something similar to what I sometimes use with `chron::times`: ``` x <- chron::times( "10:25:00" ) n <- as.numeric( x ) n [1] 0.4340278 chron::times( n ) [1] 10:25:00 ``` Is a similar (except using integers instead of numbers/doubles/floats) method available with the `ITime` class? Note I'm aware of the same "origin required" issue with `IDate`, `Date`, etc., but that makes more sense to me since `origin="1970-01-01"` is a lot less of a robust standard compared with using "midnight" as an origin for time (I use some data sources with different ideas on which date should be called the "origin").