有没有一种简单的方法来计算两个 date_times 之间的分钟数,不包括特定的时间间隔?

问题描述

start                   End                  minutes
2019-01-11 14:36:00     2019-01-13 16:27:00  2991

我想要的是计算分钟,不包括 00:00 和 06:00 之间的时间间隔。

解决方法

interval_time_excluded=as.numeric(round(difftime("2019-01-13 16:27:00","2019-01-11 14:36:00",units = "days")))*as.difftime(c("06:00:00","00:00:00"),units = "mins")[1]
interval_time_excluded
# output : Time difference of 720 mins
difftime("2019-01-13 16:27:00",units = "mins")
# output : Time difference of 2991 mins
difftime("2019-01-13 16:27:00",units = "mins")-interval_time_excluded
# Your desired output : Time difference of 2271 mins
,

您的帖子问题很简单,只是您需要更多练习 apply 之类的 R 函数:

end_date="2019-01-11 14:36:00"
start_date="2019-01-13 16:27:00"
start_date_excluded="00:00:00"
end_date_excluded="06:00:00"


diff_times<-function(start_date="2019-01-13 16:27:00",end_date="2019-01-11 14:36:00",start_date_excluded="00:00:00",end_date_excluded="06:00:00"){
        interval_time_excluded=as.numeric(round(difftime(start_date,end_date,units = "days")))*as.difftime(c(end_date_excluded,start_date_excluded),units = "mins")[1]
        # interval_time_excluded
        # output : Time difference of 720 mins
    
    # part for the special case 
# part for the special case 
if(round(difftime(start_date,units = "days"))==0){
   

if(c(as.numeric(lubridate::hour(start_date))+1)==as.numeric(substr(end_date_excluded,1,2)) & as.numeric(substr(start_date_excluded,2))==as.numeric(lubridate::hour(end_date))) { 
      return(0)   
    }else{
        return(difftime(start_date,units = "mins"))
    }  
}

# part for the special case

    # part for the special case
    
    # difftime(start_date,units = "mins")
    # output : Time difference of 2991 mins
    return(difftime(start_date,units = "mins")-interval_time_excluded)
        # Your desired output : Time difference of 2271 mins
        
}
    
    

    diff_times()  # An example of a running using the default entered function values
    
    data=structure(list(BLOCK_DATE_TIME.x = structure(c(1547217360,1547225100,1547392800,1554900060,1555930500,1556305620),class = c("POSIXct","POSIXt"),tzone = "UTC"),BLOCK_DATE_TIME.y = structure(c(1547396820,1547228280,1547397600,1554905520,1555936980,1556362320),tzone = "UTC")),row.names = c(NA,6L),class = "data.frame") 

    apply(data,function(x) return(diff_times(x[2],x[1],end_date_excluded="06:00:00")))  # The result using your data ( returned as a vector ) 

这个输出:

Time difference of 2271 mins
   1    2    3    4    5    6 
2271   53   80   91  108  585 

特殊情况的例子:

diff_times(start_date="2019-01-09 05:59:00",end_date="2019-01-09 00:00:00",end_date_excluded="06:00:00")

diff_times(start_date="2019-01-09 07:59:00",end_date_excluded="06:00:00")

[1] 0
Time difference of 479 mins