Python:每天两个日期时间之间的小时数

时间:2018-09-10 12:32:08

标签: python python-datetime

我试图开发一个Python函数来确定两个datetime对象之间的差异。我需要一种算法来计算每天的小时数。有内置的功能吗?

from datetime import datetime, timedelta, date

def getHoursByDay(dateA, dateB):
    ...

dateA = datetime.strptime('2018-09-01 09:00:00', '%Y-%m-%d %H:%M:%S')
dateB = datetime.strptime('2018-09-03 11:30:00', '%Y-%m-%d %H:%M:%S')

hours = getHoursByDay(dateA, dateB)

print hours

# {
#   '2018-09-01': 15,
#   '2018-09-02': 24,
#   '2018-09-03': 11.5,
# }

3 个答案:

答案 0 :(得分:1)

虽然内置函数很简单,但是没有内置函数。

from datetime import datetime, timedelta, time

def deltaByDay(dateA, dateB):
    dateAstart = datetime.combine(dateA, time())
    dateBstart = datetime.combine(dateB, time())
    result = {}
    oneday = timedelta(1)
    if dateAstart == dateBstart:
        result[dateA.date()] = dateB - dateA
    else:
        nextDate = dateAstart + oneday
        result[dateA.date()] = nextDate - dateA
        while nextDate < dateBstart:
            result[nextDate.date()] = oneday
            nextDate += oneday
        result[dateB.date()] = dateB - dateBstart
    return result

def deltaToHours(delta, ndigits=None):
    return delta.days * 24 + round(delta.seconds / 3600.0, ndigits)

dateA = datetime.strptime('2018-09-01 09:00:00', '%Y-%m-%d %H:%M:%S')
dateB = datetime.strptime('2018-09-03 11:30:00', '%Y-%m-%d %H:%M:%S')
deltas = deltaByDay(dateA, dateB);
output = {k.strftime('%Y-%m-%d'): deltaToHours(v, 1) for k, v in deltas.items()}
print(output)
# => {'2018-09-01': 15.0, '2018-09-02': 24.0, '2018-09-03': 11.5}

答案 1 :(得分:0)

内置的timedelta函数可以使您获得总天数以及剩余的小时数差异。如果要以字典格式发布输出,则必须手动创建它,如下所示:

from datetime import datetime, time, timedelta

def getHoursByDay(dateA, dateB):
    if dateA.strftime("%Y-%m-%d") == dateB.strftime("%Y-%m-%d"):
        return {dateA.strftime("%Y-%m-%d"): abs(b-a).seconds / 3600} 
    result = {}
    delta = dateB - dateA
    tomorrow = dateA + timedelta(days=1)
    day1 = datetime.combine(tomorrow, time.min) - dateA
    result[dateA.strftime("%Y-%m-%d")] = day1.seconds / 3600
    for day in range(1, delta.days):
        result[(dateA + timedelta(days=day)).strftime("%Y-%m-%d")] = 24
    priorday = dateB - timedelta(days1)
    lastday = dateB - datetime.combine(priorday, time.min)
    result[dateB.strftime("%Y-%m-%d")] = lastday.seconds / 3600
    return result

本质上,此函数计算第一天和最后一天的值,然后填充24之间的所有天。

答案 2 :(得分:-1)

有一种简单的方法可以做到这一点。

async function * asyncGen() {
    yield Promise.resolve(3);
    yield new Promise(done => setTimeout(done, 10000));
}

let asyncIterator = asyncGen();

asyncIterator.next();
// Expected: Promise fullfilled with {value: Promise fullfilled with 3, done: false}
// Get: Promise fullfilled with {value: 3, done: false}

asyncIterator.next();
// Expected: Promise fullfilled with
// {value: Promise pending for 10 seconds, then fullfilled with undefined, done: false}
// Get: Promise pending for 10 seconds,
// then fullfilled with {value: undefined, done: false}

我用它来计算几天的差异。

https://docs.python.org/2/library/datetime.html#datetime.timedelta