How to extract Business Hours between two different times values

前端 未结 3 1376
走了就别回头了
走了就别回头了 2021-02-06 19:19

For the evaluation of tickets processed by a help desk I would like to know how many business hours an ticket is active. I can easily subtract the times and get the total amount

3条回答
  •  终归单人心
    2021-02-06 19:52

    library(lubridate)
    
       tickets <- data.frame(open = as.POSIXct(strptime(df$open, "%m/%d/%Y %H:%M")), 
                          closed = as.POSIXct(strptime(df$closed, "%m/%d/%Y %H:%M"))
    
    
    excludeDayCount <- Vectorize(function(open, close) {
    
       # Check if the ticket was open and closed on the same day
       if (identical(as.Date(open), as.Date(close))) return (0)
    
       # All the holidays to be excluded need to be put here
       holidays <- as.POSIXct(strptime(c("12/24/2015", "12/25/2015"), 
                                      "%m/%d/%Y"))
    
       # Dates between open and close  
       day_seq <- floor_date(seq(open + days(1), close, by = "days"), "day")
    
       # Count holidays / weekend days
       return(sum(day_seq %in% holidays | wday(day_seq) %in% c(1,7)))
    
    })
    
    bizHrDiff <- function(open, close) {
    
        # Hours from the end of one work day until the start of another
        hours_between_days <- dhours(6) + dhours(8.5)
    
        # Number of days to exclude
        excl_days <- excludeDayCount(open, close)  
        # Number of days in include
        reg_days <- as.integer(as.Date(close) - as.Date(open)) - excl_days 
    
    
    
        # Total duration between dates
          span <- as.duration(interval(open, close))
          # Remove the number of holidays and weekends
          span <- span - ddays(excl_days)
          # Remove out of office hours
          span <- span - (reg_days * hours_between_days)
    
    
    
    
         # Return in hours
          return(time_length(span, unit = "hour"))
    
    
    }
    
    bizHrDiff(tickets$open, tickets$closed)
    

提交回复
热议问题