These are POSIXct/POSIXlt methods for the rounding generics.
date_floor()
rounds a datetime down to a multiple of
the specified precision
.
date_ceiling()
rounds a datetime up to a multiple of
the specified precision
.
date_round()
rounds up or down depending on what is closer,
rounding up on ties.
You can group by irregular periods such as "month"
or "year"
by using
date_group()
.
# S3 method for POSIXt date_floor( x, precision, ..., n = 1L, origin = NULL, nonexistent = NULL, ambiguous = x ) # S3 method for POSIXt date_ceiling( x, precision, ..., n = 1L, origin = NULL, nonexistent = NULL, ambiguous = x ) # S3 method for POSIXt date_round( x, precision, ..., n = 1L, origin = NULL, nonexistent = NULL, ambiguous = x )
x 
A datetime vector. 

precision 
One of:

...  These dots are for future extensions and must be empty. 
n 
A single positive integer specifying a multiple of 
origin 
An origin to start counting from.
If 
nonexistent 
One of the following nonexistent time resolution strategies, allowed to be either length 1, or the same length as the input:
Using either If If 
ambiguous 
One of the following ambiguous time resolution strategies, allowed to be either length 1, or the same length as the input:
Alternatively, Finally, If If 
x
rounded to the specified precision
.
When rounding by "week"
, remember that the origin
determines the "week
start". By default, 19700101 is the implicit origin, which is a
Thursday. If you would like to round by weeks with a different week start,
just supply an origin on the weekday you are interested in.
x < as.POSIXct("20190331", "America/New_York") x < add_days(x, 0:5) # Flooring by 2 days, note that this is not tied to the current month, # and instead counts from the specified `origin`, so groups can cross # the month boundary date_floor(x, "day", n = 2)#> [1] "20190331 EDT" "20190331 EDT" "20190402 EDT" "20190402 EDT" #> [5] "20190404 EDT" "20190404 EDT"#> [1] "20190331 EDT" "20190401 EDT" "20190401 EDT" "20190403 EDT" #> [5] "20190403 EDT" "20190405 EDT"# Note that daylight saving time gaps can throw off rounding x < as.POSIXct("19700426 01:59:59", "America/New_York") + c(0, 1) x#> [1] "19700426 01:59:59 EST" "19700426 03:00:00 EDT"# Rounding is done in naivetime, which means that rounding by 2 hours # will attempt to generate a time of 19700426 02:00:00, which doesn't # exist in this time zone try(date_floor(x, "hour", n = 2))#> Error : Nonexistent time due to daylight saving time at location 2. #> ℹ Resolve nonexistent time issues by specifying the `nonexistent` argument.# You can handle this by specifying a nonexistent time resolution strategy date_floor(x, "hour", n = 2, nonexistent = "rollforward")#> [1] "19700426 00:00:00 EST" "19700426 03:00:00 EDT"