4 回答

TA貢獻(xiàn)1780條經(jīng)驗(yàn) 獲得超5個(gè)贊
您可以使用timedeltafrom datetimemodule 從開始日期到結(jié)束日期進(jìn)行迭代,如下所示
from datetime import datetime as dt, timedelta as td
strp,strf,fmt=dt.strptime,dt.strftime,"%m-%d-%Y"
a=['10-23-2019', '10-26-2019' , '11-02-2019', '11-06-2019']
print([[strf(k,fmt) for k in (strp(i,fmt)+td(days=n) for n in range((strp(j,fmt)-strp(i,fmt)).days+1))] for i,j in zip(a[::2],a[1::2])])
輸出
[['10-23-2019', '10-24-2019', '10-25-2019', '10-26-2019'], ['11-02-2019', '11-03-2019', '11-04-2019', '11-05-2019', '11-06-2019']]

TA貢獻(xiàn)1868條經(jīng)驗(yàn) 獲得超4個(gè)贊
您可以將字符串解析為datetime對(duì)象,使用它們進(jìn)行必要的計(jì)算(通過添加timedelta對(duì)象),然后最后轉(zhuǎn)換回字符串。
為了按照問題中的指定將輸出生成為嵌套列表,臨時(shí)變量dates_out用于生成內(nèi)部列表,這些列表將附加到out循環(huán)內(nèi)的主列表 ( ) 中。
如果您想使用日-月-年排序,請(qǐng)?jiān)诔霈F(xiàn)該順序的地方將 更改'%m-%d-%Y'為。'%d-%m-%Y'
import datetime
dates = ['10-23-2019', '10-26-2019' , '11-02-2019', '11-06-2019']
format = '%m-%d-%Y'
dts = [datetime.datetime.strptime(date, format) for date in dates]
out = []
i = iter(dts)
for start, end in zip(i, i):
dt = start
dates_out = []
while dt <= end:
dates_out.append(datetime.datetime.strftime(dt, format))
dt += datetime.timedelta(days=1)
out.append(dates_out)
print(out)
這給出:
[['10-23-2019', '10-24-2019', '10-25-2019', '10-26-2019'],
['11-02-2019', '11-03-2019', '11-04-2019', '11-05-2019', '11-06-2019']]
(為了可讀性插入換行符)

TA貢獻(xiàn)1807條經(jīng)驗(yàn) 獲得超9個(gè)贊
您可以使用dateutil模塊輕松完成此操作。您可以通過執(zhí)行以下操作來安裝它pip install python-dateutil。
map(parse, lst)將日期從字符串轉(zhuǎn)換為日期時(shí)間對(duì)象;zip(*[map(parse, lst)]*2)將創(chuàng)建成對(duì)的日期時(shí)間對(duì)象,以便您可以成對(duì)地導(dǎo)航它們(start,end)。最后rrule(freq=DAILY, dtstart=start, until=end)創(chuàng)建從開始到結(jié)束的一系列日期時(shí)間對(duì)象
>>> from dateutil.rrule import rrule, DAILY
>>> from dateutil.parser import parse
>>>
>>> lst = ['10-23-2019', '10-26-2019' , '11-02-2019', '11-06-2019']
>>> res = [[dt.strftime('%m-%d-%Y') for dt in rrule(freq=DAILY, dtstart=start, until=end)] for start,end in zip(*[map(parse, lst)]*2)]
>>>
>>> print(res)
[['10-23-2019', '10-24-2019', '10-25-2019', '10-26-2019'],
['11-02-2019', '11-03-2019', '11-04-2019', '11-05-2019', '11-06-2019']]

TA貢獻(xiàn)1826條經(jīng)驗(yàn) 獲得超6個(gè)贊
datetime這是使用模塊的一種方法
前任:
import datetime
data = ['10-23-2019', '10-26-2019' , '11-02-2019', '11-06-2019']
result = []
for s, e in zip(data[::2], data[1::2]): # (10-23-2019, 10-26-2019)....
s = datetime.datetime.strptime(s, "%m-%d-%Y")
e = datetime.datetime.strptime(e, "%m-%d-%Y")
temp = []
while s <= e:
temp.append(s.strftime("%m-%d-%Y"))
s += datetime.timedelta(days=1)
if temp:
result.append(temp)
print(result)
輸出:
[['10-23-2019', '10-24-2019', '10-25-2019', '10-26-2019'],
['11-02-2019', '11-03-2019', '11-04-2019', '11-05-2019', '11-06-2019']]
添加回答
舉報(bào)