Search code examples
rdateposixct

Create a regular sequence of date-times (POSIXct) using seq()


My goal is to create a vector of POSIXct time stamps given a start, an end and a delta (15min, 1hour, 1day). I hoped I could use seq for this, but I have a problem converting between the numeric and POSIXct representation:

now <- Sys.time()
now
# [1] "2012-01-19 10:30:39 CET"
as.POSIXct(as.double(now), origin="1970-01-01", tz="CET")
# [1] "2012-01-19 09:30:39 CET"
as.POSIXct(as.double(now), origin=as.POSIXct("1970-01-01", tz="CET"), tz="CET")
# [1] "2012-01-19 09:30:39 CET"

One hour gets lost during this conversion. What am I doing wrong?


Solution

  • There is a seq() method for objects of class "POSIXt" which is the super class of the "POSIXlt" and "POSIXct" classes. As such you don't need to do any conversion.

    > now <- Sys.time()
    > tseq <- seq(from = now, length.out = 100, by = "mins")
    > length(tseq)
    [1] 100
    > head(tseq)
    [1] "2012-01-19 10:52:38 GMT" "2012-01-19 10:53:38 GMT"
    [3] "2012-01-19 10:54:38 GMT" "2012-01-19 10:55:38 GMT"
    [5] "2012-01-19 10:56:38 GMT" "2012-01-19 10:57:38 GMT"