用时间段计算

时间:2014-11-02 15:41:04

标签: python datetime

我需要你的帮助。

例如 - 工作时间:

start = datetime.datetime(2014, 11, 19, 7, 15)
end   = datetime.datetime(2014, 11, 19, 11, 15)

现在我们的工作时间为4小时。

我需要一个功能,模块或一些帮助,我可以在一天的剩余时间内#34;

例如 - 空闲时间:

freetime_begin_1 = datetime.datetime(2014, 11, 19, 0, 0)
freetime_end_1 = datetime.datetime(2014, 11, 19, 7, 15)
freetime_begin_2 = datetime.datetime(2014, 11, 19, 11, 15)
freetime_end_2 = datetime.datetime(2014, 11, 19, 23, 59)

我希望你明白我的意思。

感谢。

1 个答案:

答案 0 :(得分:0)

您可以使用此例如:

#!/usr/bin/env python
#coding:utf-8
import datetime


def dt_desc(dt):
    dt = str(dt)
    days = dt[:-8]
    dt = str(dt)[-8:]
    h,m,s = map(lambda s:int(s.strip()),dt.split(":"))

    ret = "%s"%days if len(days)!=0 else ""
    ret += "%s hours "%h if h != 0 else ""
    ret += "%s minutes "%m if m != 0 else ""
    ret += "%s seconds"%s if s != 0 else ""
    return ret

start = datetime.datetime(2014, 11, 19, 7, 15)
end   = datetime.datetime(2014, 11, 19, 11, 15)
print dt_desc(end-start)

freetime_begin_1 = datetime.datetime(2014, 11, 19, 0, 0)
freetime_end_1 = datetime.datetime(2014, 11, 19, 7, 14)
freetime_begin_2 = datetime.datetime(2014, 11, 19, 11, 16)
freetime_end_2 = datetime.datetime(2014, 11, 19, 23, 59)

print dt_desc(freetime_end_1 - freetime_begin_1)
print dt_desc(freetime_end_2 - freetime_begin_2)

freetime_begin_3 = datetime.datetime(2014, 1, 19, 11, 16)
freetime_end_3 = datetime.datetime(2014, 11, 19, 23, 59)

print dt_desc(freetime_end_3 - freetime_begin_3)