Reputation: 85
I'm reading some JSON data into R, and it stores datetime information as separate time components (year, month, hour, etc.). Given that I already have the separate pieces, it seems like it should be easy to create a POSIXlt object, given that the latter is just a list of time components.
as.POSIXlt won't accept a named list or vector of components. It is possible to create a POSIXlt by adding the appropriate class and attr to a list, but it fails without the wday and yday elements, which I don't have.
I'm aware that I can convert the list to a string and parse it, but that's so inelegant a solution I thought I'd make sure there wasn't a better way.
Edit: ISOdatetime is exactly what I was looking for. Thanks!
Upvotes: 0
Views: 96
Reputation: 263362
The ISOdate or ISOdatetime functions are clearly the ones to use but since you asked how to do it with POSIXlt as a starting point here's a bit of hacking:
test <- as.POSIXlt("1970-01-01")
dput(test)
structure(list(sec = 0, min = 0L, hour = 0L, mday = 1L, mon = 0L,
year = 70L, wday = 4L, yday = 0L, isdst = 0L, zone = "PST",
gmtoff = NA_integer_), .Names = c("sec", "min", "hour", "mday",
"mon", "year", "wday", "yday", "isdst", "zone", "gmtoff"), class = c("POSIXlt",
"POSIXt"))
test$year <- 1941
test$mon <- 12
test$mday <-7
test
#[1] "3842-01-07 PST" Wrong offset
test$year <- 41
test
#[1] "1942-01-07 PST" "An infamous date"
I suspect this is "wrong". in that I doubt the day of the week or other list items get properly rejiggered.
Upvotes: 0
Reputation: 24079
ISOdate is the command to use:
ISOdate(year, month, day, hour = 12, min = 0, sec = 0, tz = "GMT")
The function returns a POSIXct type. See ?ISOdate for more info.
Upvotes: 1