指定时间序列的开始和结束

时间:2018-01-23 06:30:36

标签: r datetime

我从here找到了一些很好的代码,它允许我在24小时内输出00:00:00到00:00:00的向量:

format(seq.POSIXt(as.POSIXct(Sys.Date()), as.POSIXct(Sys.Date()+1), by = "60 min"), "%H:%M:%S", tz="GMT")

给出:

[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"
[10] "09:00:00" "10:00:00" "11:00:00" "12:00:00" "13:00:00" "14:00:00" "15:00:00" "16:00:00" "17:00:00"
[19] "18:00:00" "19:00:00" "20:00:00" "21:00:00" "22:00:00" "23:00:00" "00:00:00"

但我想指定序列的开始和结束时间。我想我可以插入这样的东西,我无法使用seq.POSIXt

from="17:00:00", to="08:00:00",

我怎样才能得到一个好看的矢量,如下所示?非常感谢。

17:00:00, 18:00:00, ..., 08:00:00

1 个答案:

答案 0 :(得分:2)

您可以执行以下操作:

format(seq.POSIXt(as.POSIXct(Sys.Date()-7/24), as.POSIXct(Sys.Date()+8/24), by = "60 min"), "%H:%M:%S", tz="GMT")

输出:

 [1] "17:00:00" "18:00:00" "19:00:00" "20:00:00" "21:00:00" "22:00:00" "23:00:00" "00:00:00" "01:00:00" "02:00:00" "03:00:00" "04:00:00"
[13] "05:00:00" "06:00:00" "07:00:00" "08:00:00"

请注意,我所做的只是减去7/24(因为17:00是午夜前七个小时),并添加8/24,因为我们希望保留午夜后的前八个小时。