time.strptime got TypeError: function takes at most 8 arguments (9 given)

time.strptime got TypeError: function takes at most 8 arguments (9 given)

我测试了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)}]

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) is equivalent to 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)]

如果您想保留字典的其余部分,return 来自 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)}]

根据 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