r-有没有一种简单的方法可以计算两个日期时间之间的分钟数,不包括特定的时间间隔


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", "2019-01-11 14:36:00", units = "mins")
# output : Time difference of 2991 mins
difftime("2019-01-13 16:27:00", "2019-01-11 14:36: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, end_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,1,2))==as.numeric(lubridate::hour(end_date))) { 
return(0)   
}else{
return(difftime(start_date, end_date, units = "mins"))
}  
}
# part for the special case
# part for the special case

# difftime(start_date, end_date, units = "mins")
# output : Time difference of 2991 mins
return(difftime(start_date, end_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), class = c("POSIXct", "POSIXt"), tzone = "UTC")), row.names = c(NA, 6L), class = "data.frame") 
apply(data, 1 , function(x) return(diff_times(x[2],x[1],start_date_excluded="00:00:00",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",start_date_excluded="00:00:00",end_date_excluded="06:00:00")
diff_times(start_date="2019-01-09 07:59:00",end_date="2019-01-09 00:00:00",start_date_excluded="00:00:00",end_date_excluded="06:00:00")
[1] 0
Time difference of 479 mins

最新更新