按天划分日期范围,并使用Python制作列表日期间隔列表

时间:2017-05-19 13:36:01

标签: python datetime

我的日期范围如SetConfig(new HostConfig { EmbeddedResourceTreatAsFiles = { "inline.bundle.js" } }); 。所以,我想按日间隔分割这个范围并得到这样的结果:"2017-05-01", "2017-05-18"

3 个答案:

答案 0 :(得分:2)

您可以尝试此操作,首先将字符串转换为datetime并获取间隔并使用列表推导来生成列表:

from datetime import datetime,timedelta
st=["2017-05-01", "2017-05-19"]
n=2

start=datetime.strptime(st[0],"%Y-%m-%d")
end=datetime.strptime(st[1],"%Y-%m-%d")

r = [[(start+ timedelta(days=i)).strftime("%Y-%m-%d"),(start+ timedelta(days=i+1)).strftime("%Y-%m-%d")] if i!=(end-start).days else [(start+ timedelta(days=i)).strftime("%Y-%m-%d")] for i in range(0,(end-start).days+1,2)]

print r

结果:

[['2017-05-01', '2017-05-02'], ['2017-05-03', '2017-05-04'], ['2017-05-05', '2017-05-06'], ['2017-05-07', '2017-05-08'], ['2017-05-09', '2017-05-10'], ['2017-05-11', '2017-05-12'], ['2017-05-13', '2017-05-14'], ['2017-05-15', '2017-05-16'], ['2017-05-17', '2017-05-18'], ['2017-05-19']]

答案 1 :(得分:0)

创建二重奏

以下是datetime.timedelta(days=1)的解决方案。您可以轻松减少此代码。

import datetime


input_dates = ['2017-05-01', '2017-05-17']
date_format = "%Y-%m-%d" # Format

# Set the range
start_date = datetime.datetime.strptime(input_dates[0], date_format)
end_date = datetime.datetime.strptime(input_dates[1], date_format)

# You can have the difference in days with this :
delta = (end_date - start_date)
diff_days = delta.days
print "Days diff : {}".format(diff_days) # Comment it

duos_list = []

for step in xrange(0, diff_days + 1, 2):
    date_1 = start_date + (datetime.timedelta(days=1) * step)
    date_2 = date_1 + datetime.timedelta(days=1)

    duo = [date_1.strftime(date_format)]
    # Not append date_2 if not in range
    if date_2 <= end_date:
        duo.append(date_2.strftime(date_format))

    # Append the duo of date on the result list
    duos_list.append( duo )

print repr(duos_list)

输出:

Days diff : 16
[['2017-05-01', '2017-05-02'], ['2017-05-03', '2017-05-04'], ..., ['2017-05-17']]

或chunk it

在其他方法中(我认为更好的方式),您还可以列出列表:

import datetime


input_dates = ['2017-05-01', '2017-05-17']
date_format = "%Y-%m-%d" # Format
chunk_size = 2

# Set the range
start_date = datetime.datetime.strptime(input_dates[0], date_format)
end_date = datetime.datetime.strptime(input_dates[1], date_format)

# You can have the difference in days with this :
delta = (end_date - start_date)
diff_days = delta.days

print "Days diff : {}".format(diff_days)

# Create the list of date
date_list = [ (start_date + (datetime.timedelta(days=1) * x)).strftime(date_format)  for x in xrange(0, diff_days + 1)]

# Chunk this with correct size (2)
chunked_list = [date_list[i:i + chunk_size] for i in xrange(0, len(date_list), chunk_size)]

print repr(chunked_list)

输出:

Days diff : 16
[['2017-05-01', '2017-05-02'], ['2017-05-03', '2017-05-04'], ..., ['2017-05-17']]

答案 2 :(得分:0)

首先,将其分解为两个步骤:

  1. 每天从一个日期生成到另一个日期
  2. 将列表[a,b,c,d]转换为成对[[a,b],[c,d]]
  3. 第一步,这里有一个答案:Iterating through a range of dates in Python 其中定义了以下生成器:

    from datetime import timedelta, date
    
    def daterange(start_date, end_date):
        for n in range(int ((end_date - start_date).days)):
            yield start_date + timedelta(n)
    

    如果我们然后使用the itertools documentation中的这个定义配对那些:

    def grouper(iterable, n, fillvalue=None):
        "Collect data into fixed-length chunks or blocks"
        # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
        args = [iter(iterable)] * n
        return zip_longest(*args, fillvalue=fillvalue)
    

    那么我们可以将它们组合在一起以制作所需的生成器:

    daypairs = grouper(daterange(start_date, end_date), 2)
    

    因此使其变得神圣:

    daypairslist = list(daypairs)