2024-10-05 14:27:10 发布
网友
我想计算一天的工作时间,并从中减去午餐时间。所以有人8:00打卡上班,12:00到12:30吃午饭,16:00吃完。 午餐时间在设置表中配置,包括开始时间和结束时间。你知道吗
简而言之,我想计算一下:
结束时间减去开始时间=n小时:分钟工作,减去午餐时间(=12:30-12:00=30分钟)
如何在Python中计算它而不使它成为硬编码的东西? 如果您能帮忙,我们将不胜感激
干杯
您可以使用Python datetime执行此操作:
import datetime as dt def work_time(start, end, lunch=[], format_='%H:%M'): """ Calculate the hours worked in a day. """ start_dt = dt.datetime.strptime(start, format_) end_dt = dt.datetime.strptime(end, format_) if lunch: lunch_start_dt = dt.datetime.strptime(lunch[0], format_) lunch_end_dt = dt.datetime.strptime(lunch[1], format_) lunch_duration = lunch_end_dt - lunch_start_dt else: lunch_duration = dt.timedelta(0) elapsed = end_dt - start_dt - lunch_duration hours = elapsed.seconds / 3600 return hours
>>> work_time('8:00', '16:00', lunch=['12:00', '12:30']) 7.5
datetime的documentation提供了有关特定格式以及如何使用timedelta对datetime和time对象执行操作的更多信息。你知道吗
您可以使用Python datetime执行此操作:
datetime的documentation提供了有关特定格式以及如何使用timedelta对datetime和time对象执行操作的更多信息。你知道吗
相关问题 更多 >
编程相关推荐