如何计算两个日期之间的营业时间(R语言)?

问题描述 投票:0回答:1

如何计算两个事件日期之间的工作时间:时间?

我正在寻找R代码给我大约9个工作小时(而不是71个小时)!我如何从日历中删除周末时间,假日时间,并将工作时间从上午8点设置为下午5点?

任何提示都会很好。谢谢,

Date1 <- parse_date_time("2019-04-12 3:00:12 PM", order=c("%Y-%m-%d %I:%M:%S %p"), tz = "EST")

Date2 <- parse_date_time("2019-04-15 2:30:44 PM", order=c("%Y/%m/%d %I:%M:%S %p"), tz = "EST")


# This code give me roughly an answer of one day
sum(!weekdays(seq(Date1, Date2, "days")) %in% c("Saturday", "Sunday"))

# This code give me the amount of hours: 70.69 hours but include the weekend! 
round(difftime(Date2, Date1, units="hour"), 2)

我期待在15:00的周五活动和周一的14:30的闭幕活动之间获得9小时(工作时间)。 (另外,不包括1小时的午餐)。

r
1个回答
0
投票

这不包括假期,但如果需要,将很容易考虑

 Date1 <- parse_date_time("2019-04-04 3:00:12 PM", order=c("%Y-%m-%d %I:%M:%S %p"), tz = "EST")

 Date2 <- parse_date_time("2019-04-15 2:30:44 PM", order=c("%Y/%m/%d %I:%M:%S %p"), tz = "EST")

 #8AM to 5PM
 sw=8
 ew=17
  df=data.frame(Day=c(seq(Date1, Date2, "days"),Date2))
 df$day=strftime(df$Day,'%A')
 df$nday=as.numeric(format(df$Day,"%u"))
 # fill hours
 df$nH=NA
 for (i in 2:nrow(df))df$nH[i]=ew-sw-1
 # exclude weekeds 
 df=df[!df$nday %in% c(6,7),]
 #adjust  first and last day
 df$nH[1]=as.numeric(ew-as.difftime(format(df$Day[1],"%H:%M:%S"),units = "hours"))
 df$nH[nrow(df)]=as.numeric(as.difftime(format(df$Day[nrow(df)],"%H:%M:%S"),units = "hours")-sw)-1
 sum(df$nH)



# > sum(df$nH)
 # [1] 55.50889
 # > df
 # Day           day nday       nH
 # 1  2019-04-04 15:00:12  quinta-feira    4 1.996667
 # 2  2019-04-05 15:00:12   sexta-feira    5 8.000000
 # 5  2019-04-08 15:00:12 segunda-feira    1 8.000000
 # 6  2019-04-09 15:00:12   terça-feira    2 8.000000
 # 7  2019-04-10 15:00:12  quarta-feira    3 8.000000
 # 8  2019-04-11 15:00:12  quinta-feira    4 8.000000
 # 9  2019-04-12 15:00:12   sexta-feira    5 8.000000
 # 12 2019-04-15 14:30:44 segunda-feira    1 5.512222
© www.soinside.com 2019 - 2024. All rights reserved.