如何从日期(字符串)范围创建dict?

时间:2015-06-18 10:06:34

标签: python python-2.7

我有两个日期作为字符串:

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],
}

如何从这两个字符串生成密钥?

1 个答案:

答案 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>