项目场景:
进入了一个项目,需要计算工时,很烦人,所以手写了一个python脚本计算每天工时,目前是个初步版本,后面会继续改进。
项目实际要求如下:
- 实际工作时间9:00-17:30,算7个小时工作时长,也就是说中间有一个半小时不算时长,所以我将11:30-13:00算吃饭时间,实际可能不一样,后续等具体确认再修改吧。
- 早晨8:00开始算时间,早于8点也算8点开始
- 晚上17:30-18:30算吃饭时间,所以如果这个时间段下班,那么就算17点30分下班,加班时间要把这个时间段减掉。
代码如下:
import csv
from datetime import *
DAY_SECOND = 24 * 60 * 60
HOUR_SECOND = 60 * 60
MINUTE_SECOND = 60
with open('./averageWorkHour.csv','r', encoding='utf-8') as workFile:
lines = csv.reader(workFile)
#print(lines.info)
lunchStart = datetime.strptime("11:30:00","%H:%M:%S")
lunchEnd = datetime.strptime("13:00:00","%H:%M:%S")
supperStart = datetime.strptime("17:30:00","%H:%M:%S")
supperEnd = datetime.strptime("18:30:00","%H:%M:%S")
totalManHour = datetime.strptime("00:00:00","%H:%M:%S")
#setworktimestart是给定的工时,8点后才能算工时
setWorkTimeStart = datetime.strptime("8:00:00","%H:%M:%S")
#setworktimeend是给定的工时,17:30-18:30之间为晚饭时间,所以这段时间不算工时
setWorkTimeEnd1 = datetime.strptime("17:30:00","%H:%M:%S")
setWorkTimeEnd2 = datetime.strptime("18:30:00","%H:%M:%S")
# workDayNum 计算表格中有多少天
workDayNum = 0
for line in lines:
workDayNum = workDayNum + 1
# print(line[0],line[1],"workDayNum", workDayNum)
# 上班时间,但是要注意如果上班时间早于八点,实际还是按照8点算
toWork = max(datetime.strptime(line[1],"%H:%M:%S"), setWorkTimeStart)
# 下班时间如果在17:30-18:30之间,则默认为17:30
offWork = datetime.strptime(line[2],"%H:%M:%S")
if offWork >= setWorkTimeEnd1 and offWork <= setWorkTimeEnd2:
offWork = setWorkTimeEnd1
morningTime = lunchStart - toWork
# 防止上午来了急事直接请假, afternoontime 应该为0
if offWork < lunchStart:
morningTime = offWork - toWork
afternoonTime = lunchStart - lunchStart
# 或者上午没来,下午来了且没有加班
elif toWork > lunchEnd and offWork < supperEnd:
morningTime = lunchStart - lunchStart
afternoonTime = offWork - lunchEnd
# 或者上午没来,下午来了且加班了
elif toWork > lunchEnd and offWork > supperEnd:
morningTime = lunchStart - lunchStart
afternoonTime = supperStart - toWork + offWork - supperEnd
# 正常上班,没有加班
elif offWork < supperEnd:
afternoonTime = offWork - lunchEnd
# 正常上班,且有加班
else:
afternoonTime = supperStart - lunchEnd + offWork - supperEnd
dayTime = morningTime + afternoonTime
totalManHour = totalManHour + dayTime
print(line[0],"DayTime",dayTime)
all = (totalManHour.day - 1) * DAY_SECOND + totalManHour.hour * HOUR_SECOND + totalManHour.minute * MINUTE_SECOND + totalManHour.second
aveDay = all / workDayNum
avHour = aveDay // HOUR_SECOND
avSecond = aveDay % MINUTE_SECOND
avMinute = (aveDay % HOUR_SECOND - avSecond) / MINUTE_SECOND
# 目前工作市场要求是8.5个小时,所以判断条件是这个,根据实际修改
if (avHour == 8 and avMinute >= 30) or (avHour > 8):
print("Congratulations Your Average Day Time is ",int(avHour),":",int(avMinute),":",int(avSecond))
else:
gap = (8 - avHour) * 60 + 30 - avMinute
print("Your should work over time, your hour gap is ", gap," minutes every day ", "Your Average Day Time",int(avHour),":",int(avMinute),":",int(avSecond))