Search code examples
rxtslubridate

How can I in R cleverly find previous time periods start and end?


I would in R like to find the previous periods beginning and end. A period is defined in minutes.

Would love the output as below.

library(lubridate)
timeNow <- now()
timeNow
# [1] "2019-04-17 11:17:09 CEST"

periodLength <- 60    #minutes
previousPeriodStart(timeNow, periodLength)
# [1] "2019-04-17 10:00:00 CEST"
previousPeriodEnd(timeNow, periodLength)
# [1] "2019-04-17 10:59:59 CEST"

periodLength <- 5    #minutes
previousPeriodStart(timeNow, periodLength)
# [1] "2019-04-17 11:10:00 CEST"
previousPeriodEnd(timeNow, periodLength)
# [1] "2019-04-17 11:14:59 CEST"

I understand how to build these functions in xts if I had a ts with data. As I don't have a dataset for this example I can't use xts to.period functions. I instead just want to find the start and end.

What would be the most clever way of constructing the previousPeriodStart and previousPeriodEnd? Or should I just start doing some arithmetic with epoch/unix times?

Big thanks in advance.

--- EDIT ---- Since receiving an answer with a function that answers both start and end in same function this is of course much smarter.


Solution

  • With lubridate this can easily be done:

    previousPeriod <- function(timeNow,periodLength)
    {
      start <- floor_date(timeNow - minutes(60),"hour")
      end <- ceiling_date(timeNow - minutes(60),"hour") - seconds(1)
      return(c(start=start,end=end))
    }
    
    previousPeriod(timeNow,periodLength)
    
                        start                       end 
    "2019-04-17 10:00:00 UTC" "2019-04-17 10:59:59 UTC"