Rounding time to nearest quarter hour

前端 未结 7 628
清酒与你
清酒与你 2020-12-03 13:43

I have a vector of POSIXct values and I would like to round them to the nearest quarter hour. I don\'t care about the day. How do I convert the values to hours and minutes?<

7条回答
  •  渐次进展
    2020-12-03 14:00

    You can use round. The trick is to divide by 900 seconds (15 minutes * 60 seconds) before rounding and multiply by 900 afterwards:

    a <-as.POSIXlt("2012-05-30 20:41:21 UTC")
    b <-as.POSIXlt(round(as.double(a)/(15*60))*(15*60),origin=(as.POSIXlt('1970-01-01')))
    b
    [1] "2012-05-30 20:45:00 EDT"
    

    To get only hour and minute, just use format

    format(b,"%H:%M")
    [1] "20:45"
    
    as.character(format(b,"%H:%M"))
    [1] "20:45"
    

提交回复
热议问题