time.strptime得到TypeError:函数最多需要8个参数(给定9个)

时间:2016-01-08 09:14:52

标签: python datetime strptime

我测试了time.strptime();它有效:

In [2]: time.strptime(u'1994-03-30T00:00:00.000Z','%Y-%m-%dT%H:%M:%S.%fZ')
Out[2]: time.struct_time(tm_year=1994, tm_mon=3, tm_mday=30, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=89, tm_isdst=-1)

但得到了:

TypeError: function takes at most 8 arguments (9 given)

代码如下:

import datetime
import time

data = [{u'volume': 249675300.0, u'date': u'1994-03-31T00:00:00.000Z'}, \
        {u'volume': 202356800.0, u'date': u'1994-03-30T00:00:00.000Z'}]   

map(lambda x:datetime.datetime(*time.strptime(x['date'],'%Y-%m-%dT%H:%M:%S.%fZ')), data )
print data

我希望用datetime个对象替换所有日期字符串,保留其余部分:

[{u'volume': 249675300.0, u'date': datetime.datetime(1994, 3, 31, 0, 0)}, 
 {u'volume': 202356800.0, u'date': datetime.datetime(1994, 3, 30, 0, 0)}]

2 个答案:

答案 0 :(得分:2)

datetime.datetime()不接受wdayydayis_dst参数;你必须把时间元组切换到前6个元素。

您无需在此处使用time.strptime(),只需使用datetime.datetime.strptime()

map(lambda x: datetime.datetime.strptime(x['date'], '%Y-%m-%dT%H:%M:%S.%fZ'), data)

另见datetime documentation on using strptime()

  

datetime.strptime(date_string, format)相当于datetime(*(time.strptime(date_string, format)[0:6]))

演示:

>>> import time
>>> import datetime
>>> time.strptime(u'1994-03-30T00:00:00.000Z','%Y-%m-%dT%H:%M:%S.%fZ')
time.struct_time(tm_year=1994, tm_mon=3, tm_mday=30, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=89, tm_isdst=-1)
>>> datetime.datetime(*time.strptime(u'1994-03-30T00:00:00.000Z','%Y-%m-%dT%H:%M:%S.%fZ')[:6])
datetime.datetime(1994, 3, 30, 0, 0)
>>> datetime.datetime.strptime(u'1994-03-30T00:00:00.000Z','%Y-%m-%dT%H:%M:%S.%fZ')
datetime.datetime(1994, 3, 30, 0, 0)

并使用您的示例输入:

>>> data = [{u'volume': 249675300.0, u'date': u'1994-03-31T00:00:00.000Z'},
...         {u'volume': 202356800.0, u'date': u'1994-03-30T00:00:00.000Z'}]
>>> map(lambda x: datetime.datetime.strptime(x['date'], '%Y-%m-%dT%H:%M:%S.%fZ'), data)
[datetime.datetime(1994, 3, 31, 0, 0), datetime.datetime(1994, 3, 30, 0, 0)]

如果您想保留字典的其余部分,请从map()函数返回一个新字典,并替换'date'键:

map(lambda x: dict(x, date=datetime.datetime.strptime(x['date'], '%Y-%m-%dT%H:%M:%S.%fZ')), data)

这会产生:

[{u'volume': 249675300.0, u'date': datetime.datetime(1994, 3, 31, 0, 0)}, {u'volume': 202356800.0, u'date': datetime.datetime(1994, 3, 30, 0, 0)}]

答案 1 :(得分:0)

根据Martijn Pieters的回答,

import datetime

data = [{u'volume': 249675300.0, u'date': u'1994-03-31T00:00:00.000Z'},\
    {u'volume': 202356800.0, u'date': u'1994-03-30T00:00:00.000Z'}]

def transdate(dict_):
    dict_['date'] = datetime.datetime.strptime(dict_['date'], '%Y-%m-%dT%H:%M:%S.%fZ')
    return dict_

data = map(trans, data)
print data