在Python中获取日期时间范围之间的小时数

时间:2018-10-16 18:12:43

标签: python datetime

因此,我尝试按如下所示在python中的开始日期和结束日期之间的间隔中打印总时数:

@app.route('/test/')
def test():

date_format = "%Y-%m-%d %H:%M:%S"
start_date_time = datetime.strptime("2018-10-16 07:00:00", date_format)
end_date_time = datetime.strptime("2018-10-18 22:00:00", date_format)

def daterange(start_date_time, end_date_time):
    for n in range(int ((end_date_time - start_date_time).days)):
        yield start_date_time + timedelta(n)

for single_date in daterange(start_date_time, end_date_time):
    def get_delta(start_date_time, end_date_time):
        delta = end_date_time - start_date_time
        return delta

# Split time in hours
delta = get_delta(start_date_time,end_date_time)
for i in range(delta.days * 24 + 1): # THIS IS ONLY CALCULATING 24HRS FROM TIME GIVEN START TIME NOT TILL THE SELECTED END TIME SO I'M ONLY GETTING AN EXACT 24 HOUR RANGE
    currtime = start_date_time + timedelta(hours=i)

    print (currtime)
return ("done")

通过这种方式,我只设法获得从所选日期开始的前24小时,但我希望继续计数,并获得直到所选结束日期的所有小时数。

1 个答案:

答案 0 :(得分:2)

您可能想得太多。

from datetime import datetime, timedelta

date_format = "%Y-%m-%d %H:%M:%S"
start_date_time = datetime.strptime("2018-10-16 07:00:00", date_format)
end_date_time = datetime.strptime("2018-10-18 22:00:00", date_format)

def get_delta(l, r):
    return abs(int((l-r).total_seconds())) / 3600

for h in range(int(get_delta(start_date_time, end_date_time))):
    print((start_date_time + timedelta(0, h*3600)).strftime(date_format))