【问题标题】:How to add and subtract times in python [duplicate]如何在python中添加和减去时间[重复]
【发布时间】:2016-10-18 11:20:15
【问题描述】:

我想编写一个简单的时间表脚本。我的输入文件看起来像

9:00 17:00
10:45 12:35
11:00 15:00

我想阅读它,计算每天工作的小时数,然后将这些小时数相加。当一天从 12:00 之前开始到 13:00 之后结束时,我也想减去半小时的午休时间。

到目前为止我的尝试是:

import sys
from datetime import datetime

gap = datetime.strptime('00:30','%H:%M')
hours = []
for line in sys.stdin:
    (start_time,end_time) = line.split()
    start_time = datetime.strptime(start_time, '%H:%M')
    end_time = datetime.strptime(end_time, '%H:%M')
    #if start_time before 12:00 and end_time after 13:00 then subtract gap
    hours.append(end_time-start_time)       
print sum(hours)

我不知道如何使 if 语句行起作用,并且对时间求和似乎也不起作用,因为您无法对 datetime.timedelta 类型求和。


感谢 cmets 中的链接,将 sum(hours) 替换为 reduce(operator.add, hours) 有效。

剩下的部分是如何测试 start_time 是否在 12:00 之前,end_time 是否在 13:00 之后,如果是,则将 timedelta 减少半小时。

【问题讨论】:

标签: python


【解决方案1】:

您在 if 语句中使用了不正确的代码(和语法)。

if start_time < datetime.strptime('12:00', '%H:%M') and end_time > datetime.strptime('13:00', '%H:%M'):
    delta_hours = end_time.hour - start_time.hour)
    delta_minutes = end_time.minutes - start_time.minutes)
    # Do whatever your want with it now.
    # Substraction of the break is not implemented in this example, it depends on how you want to save it.

Time delta 可能也值得研究,它可以使用诸如

之类的基本操作
a = timedelta(...)
b = timedelta(...)
c = b - a - gap

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-03
    • 1970-01-01
    • 2019-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多