Skip to content

Instantly share code, notes, and snippets.

@mikmart
Created November 9, 2019 08:26
Show Gist options
  • Save mikmart/cb2d5cbef53a392311e072a2626305ad to your computer and use it in GitHub Desktop.
Save mikmart/cb2d5cbef53a392311e072a2626305ad to your computer and use it in GitHub Desktop.
A helper function to split a time interval into multiple smaller periods
library(tidyverse)
library(lubridate)
split_interval <- function(start, end, unit) {
breaks <- seq(floor_date(start, unit), ceiling_date(end, unit), by = unit)
timeline <- c(start, breaks[breaks > start & breaks < end], end)
tibble(
.seq = seq_len(length(timeline) - 1),
.start = head(timeline, -1),
.end = tail(timeline, -1),
)
}
split_interval(now(), now() + hours(2), unit = "hours")
#> # A tibble: 3 x 3
#> .seq .start .end
#> <int> <dttm> <dttm>
#> 1 1 2019-11-09 10:25:09 2019-11-09 11:00:00
#> 2 2 2019-11-09 11:00:00 2019-11-09 12:00:00
#> 3 3 2019-11-09 12:00:00 2019-11-09 12:25:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment