Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding time to nearest quarter hour

Tags:

datetime

r

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?

For example, I would like the value

"2012-05-30 20:41:21 UTC"

to be

"20:45"
like image 824
Dominic Avatar asked Jun 02 '12 11:06

Dominic


People also ask

How do you round to the nearest quarter hour in Excel?

So, use CEILING(A2,1/96) to round up to the next higher quarter hour. Use MROUND(A2,1/96) to round to the nearest quarter hour, and then use FLOOR(A2,1/96) to round to the lower quarter hour-- always goes back.

How do you convert time into quarter hours?

Add Up Time ManuallyDivide the minutes by 60. You'll usually get a whole number followed by one or two decimal points. If you're working with quarter hours, you may be able to refer to a standard chart instead. For example, 15 minutes equals one quarter-hour, or 0.25 hours.

What does rounding to the nearest quarter mean?

For employers who track to the closest quarter hour, you should apply the “7-minute rule.” If an employee works an extra 1-7 minutes, the time can be rounded down to the closest quarter hour. If an employee works an extra 8-14 minutes, the time should be rounded up to the closest quarter hour.


3 Answers

Indeed, an old question with some helpful answers so far. The last one by giraffhere seems to be the most elegant. however, ist not floor_date but round_date which will do the trick:

lubridate::round_date(x, "15 minutes") 
like image 124
user3297928 Avatar answered Oct 22 '22 12:10

user3297928


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"
like image 31
Pierre Lapointe Avatar answered Oct 22 '22 12:10

Pierre Lapointe


something like

format(strptime("1970-01-01", "%Y-%m-%d", tz="UTC") + round(as.numeric(your.time)/900)*900,"%H:%M")

would work

like image 28
shhhhimhuntingrabbits Avatar answered Oct 22 '22 13:10

shhhhimhuntingrabbits