你可以帮助我吗,我是python的新手,这里有一个包含一些数据的列表
data_list=[[], [247L, datetime.datetime(2011, 4, 7, 0, 0), datetime.datetime(2011, 9, 14, 7, 55, 1)], [247L, datetime.datetime(2011, 4, 7, 0, 0), datetime.datetime(2011, 9, 1, 11, 59)], [247L, datetime.datetime(2011, 4, 7, 0, 0), datetime.datetime(2012, 3, 1, 11, 59)], [247L, datetime.datetime(2011, 4, 7, 0, 0), datetime.datetime(2012, 4, 29, 22, 54, 11)], [248L, datetime.datetime(2011, 4, 7, 0, 0), datetime.datetime(2012, 3, 1, 11, 59)], [254L, datetime.datetime(2011, 4, 7, 0, 0), datetime.datetime(2012, 3, 1, 11, 59)], [258L, datetime.datetime(2011, 4, 7, 0, 0)], [259L, datetime.datetime(2011, 4, 7, 0, 0), datetime.datetime(2011, 9, 14, 7, 55, 1)], [259L, datetime.datetime(2011, 5, 7, 0, 0), datetime.datetime(2012, 3, 1, 11, 59)]]
其中247,248 ..是唯一标识,我想将下面的日期提取到字典中,
data_dict={247:('2011-4-7','2011-9-1'),248:('2011-4-7','2012-3-1'),254:('2011-4-7','2012-3-1'),258:('2011-4-7', '2011-9-14'), 259:('2011-5-7','2011-9-14')}
并将此词典发送给返回此类结果的函数,147表示2个日期之间的天数
data_count={247:'147',248:'329',254:'329',258:'0',259:'130'}
我写了一个小代码来计算天数,但我不知道如何通过函数发送它
a='2011-5-7'
b='2011-9-14'
date_format = "%Y-%m-%d"
a=datetime.strptime(a, date_format)
b = datetime.strptime(b, date_format)
delta = b - a
print delta.days
这是正确的
class a:
def __init__(self):
def datedifference(self,a, b):
self.date_format = "%Y-%m-%d"
return (datetime.strptime(b, self.date_format) -datetime.strptime(a, self.date_format)).days
def main():
data_dict={247:('2011-4-7','2011-9-1'),248:('2011-4-7','2012-3-1'),254: ('2011-4-7','2012-3-1'),258:('2011-4-7',)259:('2011-5-7','2011-9-14')}
ob=a()
{k: ob.datedifference(v[0],v[1]) for k, v in data_dict.iteritems()}
答案 0 :(得分:2)
使功能变得简单:
def datedifference(a, b):
date_format = "%Y-%m-%d"
return (datetime.strptime(b, date_format) - datetime.strptime(a, date_format)).days
将其应用到您的data_dict
并非如此:
{k: datedifference(*v) for k, v in data_dict.iteritems()}
这给出了(带有修复的data_dict
输入样本):
>>> {k: datedifference(*v) for k, v in data_dict.iteritems()} {248: 329, 258: 160, 259: 130, 254: 329, 247: 147}
假设每个数据点有2个日期;如果您只有1,那么您需要调整功能以测试更少的日期。
首先生成data_dict
:
data_dict = {}
for row in data_list:
if not row: continue
key, dates = row[0], row[1:]
if key in data_dict: continue # already in there
data_dict[key] = tuple(map(datetime.date.isoformat, dates))
生成:
{248L: ('2011-04-07', '2012-03-01'), 258L: ('2011-04-07',), 259L: ('2011-04-07', '2011-09-14'), 254L: ('2011-04-07', '2012-03-01'), 247L: ('2011-04-07', '2011-09-14')}