2015-06-18 83 views
-2

我有兩個日期爲字符串:如何從日期(字符串)範圍創建字典?

start = '2015-01-01' 
end = '2015-03-23' 

我想創建這樣的dict(我用OrderedDict):

date_dict = { 
    '2015-01-01': [something], 
    '2015-01-02': [something], 
    '2015-01-03': [something], 
    '2015-01-04': [something], 
    [...] 
    '2015-03-22': [something], 
    '2015-03-23': [something], 
} 

如何從這個兩個字符串鍵?

+0

http://stackoverflow.com/a/7274316/4907653 – f43d65

+0

是你的日期始終保存爲字符串? –

回答

1

嘗試像下面的代碼生成密鑰 -

from datetime import datetime as dt, timedelta as td 
start = '2015-01-01' 
end = '2015-03-23' 
sd = dt.strptime(start,'%Y-%m-%d') 
ed = dt.strptime(end,'%Y-%m-%d') 
delta = ed - sd 
for i in range(delta.days+1): 
    dict[sd + td(days=i)] = <something>