计算python中日期之间的小时范围

时间:2016-04-28 18:18:05

标签: python datetime

如何查找日期范围内的小时数?我目前正在计算和打印两个给定日期之间的日期。

from datetime import timedelta as td, datetime

d1 = datetime.strptime(start_date, '%Y-%m-%d')
d2 = datetime.strptime(end_date, '%Y-%m-%d')

def get_delta(d1, d2):
    delta = d2 - d1
    return delta

delta = get_delta(d1,d2)
for i in range(delta.days + 1):
    print d1 + td(days=i)

当前输出:

2016-04-22
2016-04-23
2016-04-24
2016-04-25
2016-04-26
2016-04-27
2016-04-28
...

预期输出:

2016-04-22 00:00:00
2016-04-22 01:00:00
2016-04-22 02:00:00
2016-04-22 03:00:00
2016-04-22 04:00:00
2016-04-22 05:00:00
2016-04-22 06:00:00
2016-04-22 07:00:00
...

5 个答案:

答案 0 :(得分:6)

您将时间按天而不是小时递增,timedelta(days=i)而非timedelta(hours=i)

from datetime import timedelta as td, datetime

start_date = '2016-01-01'
end_date = '2016-01-02'
d1 = datetime.strptime(start_date, '%Y-%m-%d')
d2 = datetime.strptime(end_date, '%Y-%m-%d')

def get_delta(d1, d2):
    delta = d2 - d1
    return delta

delta = get_delta(d1,d2)
for i in range(delta.days * 24 + 1):
    print d1 + td(hours=i)

输出:

2016-01-01 00:00:00
2016-01-01 01:00:00
...
...
2016-01-01 23:00:00
2016-01-02 00:00:00

答案 1 :(得分:2)

为了便于阅读,要明确边缘情况中发生的语义,您可以定义类似于内置date_range()函数的range()函数:

def date_range(start, end, step):
    while start < end:
        yield start
        start += step

示例:

from datetime import datetime, timedelta

HOUR = timedelta(hours=1)

def parse(date_string):
    '''Parse *date_string* in the %Y-%m-%d format.'''
    return datetime(*map(int, date_string.split('-')))

for dt in date_range(parse(start_date), parse(end_date), HOUR):
    print(dt)

注意:输出中不存在end_date + ' 00:00:00date_range()的行为类似range(),其中不包含end。您可以传递parse(end_date) + HOUR以包含end_date

答案 2 :(得分:1)

如果你看一下timedelta对象的python文档:

  

内部只存储了几天,几秒和几微秒

因此,如果您想要获得时间,则必须从秒开始转换它。

类似的东西:

for i in range(delta.seconds / 3600 + delta.days * 24):
    print d1 + td(seconds=3600 * i)

答案 3 :(得分:1)

尝试这样的事情:

import datetime

d1 = datetime.datetime(2016, 4, 28)
d2 = d1 + datetime.timedelta(days = 2)

delta = (d2 - d1).total_seconds()/3600
for i in range(int(delta)):
    print(d1 + datetime.timedelta(hours=i))

答案 4 :(得分:0)

使用熊猫

import pandas as pd
datelist = pd.date_range(start = pd.datetime(2016, 1, 1, 0),
                         end = pd.datetime(2016, 1, 2, 0),
                         freq = "H")