如何计算两个活动日期(时间)之间的工作时间?
我正在寻找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个小时的午餐时间。)
答案 0 :(得分: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