我有一个小时的矢量。 例如:
vec.hours <- c("15:52:00", "15:56:00", "12:10:00", "15:12:00", "11:49:00" ,"13:35:00", "14:53:00")
我想花几个小时来获得最接近整整5分钟的新时间, 像这样。
round.hours <- c("15:50:00", "16:00:00", "12:10:00", "15:10:00", "11:50:00" ,"13:35:00", "14:55:00" )
我试过这个
hour <- strptime(vec.hours , "%H:%M:%S")
round.hour <- round(hour , "mins")
但它不起作用。
每轮比赛结束后我想做+/-一小时,例如:
hour.rd <- strptime(round.hours[1] , "%H:%M:%S")
hourM <- hour.rd - 3600
hourP <- hour.rd + 3600
l.tm <- timeSequence(from = hourM, to = hourP,format = "%H-%S-%M",by="5 min",FinCenter = "Europe/Zurich")
所以,在15:50:00,我有一个从14:50到16:50的矢量。
我不知道如何从vec.hours获得round.hour。
非常感谢
答案 0 :(得分:9)
我会将小时数转换为datetime对象,将它们转换为POSIXlt
,这允许您以整数形式访问分钟,使用整数除法进行舍入,然后再次提取小时数。
timestamps <- as.POSIXlt(as.POSIXct('1900-1-1', tz='UTC') + as.difftime(vec.hours))
timestamps$min <- (timestamps$min + 5/2) %/% 5 * 5
format(timestamps, format='%H:%M:%S')
# [1] "15:50:00" "15:55:00" "12:10:00" "15:10:00" "11:50:00" "13:35:00" "14:55:00"
答案 1 :(得分:9)
Lubridate包具有非常友好的round_date
功能。
round_date(hour,unit="5 minutes")
[1] "2017-08-28 15:50:00 UTC" "2017-08-28 15:55:00 UTC"
[3] "2017-08-28 12:10:00 UTC" "2017-08-28 15:10:00 UTC"
[5] "2017-08-28 11:50:00 UTC" "2017-08-28 13:35:00 UTC"
[7] "2017-08-28 14:55:00 UTC"
答案 2 :(得分:2)
从xts
包中,您可以使用align.time
# align to next whole 5 min interval
align.time(hour, 5*60)
[1] "2013-06-14 15:55:00 CEST" "2013-06-14 16:00:00 CEST" "2013-06-14 12:15:00 CEST" "2013-06-14 15:15:00 CEST"
[5] "2013-06-14 11:50:00 CEST" "2013-06-14 13:40:00 CEST" "2013-06-14 14:55:00 CEST"
这会将时间戳更改为下一个时段的开头,与OP略有不同,即开始最近时段。
答案 3 :(得分:0)
另一种选择,基于答案here - 在除以300(5分钟* 60秒)后舍入,然后将结果乘以300:
format(as.POSIXlt(as.POSIXct('2000-1-1', "UTC") +
round(as.numeric(hours)/300)*300),
format = "%H:%M:%S")
#[1] "15:50:00" "15:55:00" "12:10:00" "15:10:00" "11:50:00" "13:35:00" "14:55:00"