Search code examples
rchron

Sequence of only time (no dates) in r


I am trying to make a sequence that only consists of times with one hour interval, without dates. It should look like this:

"00:00:00" "1:00:00" "2:00:00" "3:00:00"

I know that this code works:

dat <- seq(
  from=as.POSIXct("00:00:00","%H:%M:%S", tz="UTC"),
  to=as.POSIXct("23:00:00", "%H:%M:%S", tz="UTC"),
  by="hour"
)

Which gives

[1] "2018-04-10 00:00:00 UTC" "2018-04-10 01:00:00 UTC" "2018-04-10 02:00:00 UTC" "2018-04-10 03:00:00 UTC" "2018-04-10 04:00:00 UTC"
 [6] "2018-04-10 05:00:00 UTC" "2018-04-10 06:00:00 UTC" "2018-04-10 07:00:00 UTC" "2018-04-10 08:00:00 UTC" "2018-04-10 09:00:00 UTC"
[11] "2018-04-10 10:00:00 UTC" "2018-04-10 11:00:00 UTC" "2018-04-10 12:00:00 UTC" "2018-04-10 13:00:00 UTC" "2018-04-10 14:00:00 UTC"
[16] "2018-04-10 15:00:00 UTC" "2018-04-10 16:00:00 UTC" "2018-04-10 17:00:00 UTC" "2018-04-10 18:00:00 UTC" "2018-04-10 19:00:00 UTC"
[21] "2018-04-10 20:00:00 UTC" "2018-04-10 21:00:00 UTC" "2018-04-10 22:00:00 UTC" "2018-04-10 23:00:00 UTC"

But that is not what I want. Therefore I tried

library(chron)
seq(from = times("00:00:00"), to =times("23:00:00"), by="hour")

which gives an error

Error in convert.times(times., fmt) : format h:m:s may be incorrect
In addition: Warning message:
In unpaste(times, sep = fmt$sep, fnames = fmt$periods, nfields = 3) :
  wrong number of fields in entry(ies) 1

I am stuck now, so I hope somebody can help me with this. Of course I could just type it out, but I want to have a clean solution.


Solution

  • Using package chron which provides a times class:

    library(chron)
    times("00:00:00") + (0:23)/24
    #[1] 00:00:00 01:00:00 02:00:00 03:00:00 04:00:00 05:00:00 06:00:00 07:00:00 08:00:00 09:00:00 10:00:00 11:00:00 12:00:00 13:00:00 14:00:00
    #[16] 15:00:00 16:00:00 17:00:00 18:00:00 19:00:00 20:00:00 21:00:00 22:00:00 23:00:00