0

你能帮帮我吗,我是 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()}  
4

1 回答 1

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')}
于 2013-03-26T10:24:20.117 回答