Difference between two dates, except weekends

I have two date columns in my date frame. I can find the difference between these dates using:

issues <- transform(issues, duration = difftime(strptime(close_date, format="%d.%m.%Y"), 
                                                strptime(created_on, format = "%d.%m.%Y"), units="days"))

Is there a way to find the duration of questions excluding weekends (Saturdays and Sundays)?

Update

I tried using the @agstudy solution:

getDuration <- function(d1, d2) {  
  myDays <- seq.Date(to = as.Date(d2, format="%d.%m.%Y"), 
                     from = as.Date(d1, format = "%d.%m.%Y"), by=1)
  result <- length(myDays[!is.weekend(myDays)])
  return(result)
}

issues <- transform(issues, duration = getDuration(created_on, close_date))

But get the error:

Error in seq.Date(to = as.Date(d2, format = "%d.%m.%Y"), from = as.Date(d1,  : 
  'from' must be length 1 

Why?

+4
source share
2 answers

Another option is to create a sequence of dates, exclude weekends, and calculate its length.

library(chron)
length(myDays[!is.weekend(myDays)])

Here is an example:

library(chron)
myDays <- 
seq.Date(to = as.Date('01.05.2014', format="%d.%m.%Y"), 
         from=as.Date('01.01.2014', format = "%d.%m.%Y"),by=1)
length(myDays)
length(myDays[!is.weekend(myDays)])

EDIT

You must vectorize your function in order to use it with vectors.

getDuration <- function(d1, d2,fmt="%d.%m.%Y") {  
  myDays <- seq.Date(to   = as.Date(d2, format=fmt), 
                     from = as.Date(d1, format =fmt), 
                     by   = 1)
  length(myDays[!is.weekend(myDays)]
}

Here I use mapply:

mapply(getDuration ,issues$created_on,issues$close_date)
+6
source

First you can determine the number of days off between two dates:

no_weekend_days = function(start_date, stop_date) {
    vector_with_days = strftime(seq(start, stop, by = 24 * 3600), '%A')
    return(sum(vector_with_days %in% c('Saturday', 'Sunday')))
}

And an example that uses this function:

start = as.POSIXct('2014-04-10')
stop = as.POSIXct('2014-04-21')
difftime(stop, start)
# > Time difference of 11 days
difftime(stop, start) - no_weekend_days(start, stop)
# > Time difference of 7 days
+2

Source: https://habr.com/ru/post/1536220/


All Articles