使用time.struct_time的structseq()错误

时间:2012-03-04 01:29:53

标签: python time python-2.7

这是给出错误的python脚本:

>>> import time
>>> t=[ ]        
>>> t.append(time.struct_time(tm_year=2000, tm_mon=11, tm_mday=30, tm_hour=0,tm_min=0,tm_sec=0, tm_wday=3, tm_yday=335, tm_isdst=-1))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: structseq() takes at most 2 arguments (9 given)

这个也给出了同样的错误:

>>> import time 
>>> t=time.struct_time(tm_year=2000, tm_mon=11, tm_mday=30, tm_hour=0,tm_min=0,tm_sec=0, tm_wday=3, tm_yday=335, tm_isdst=-1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: structseq() takes at most 2 arguments (9 given)

1 个答案:

答案 0 :(得分:5)

time.struct_time期望它的第一个参数是一个包含9个元素的序列:

In [58]: time.struct_time((2000,11,30,0,0,0,3,335,-1))
Out[58]: time.struct_time(tm_year=2000, tm_mon=11, tm_mday=30, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=335, tm_isdst=-1)

但请注意,这会过度指定日期时间。

例如,您可以将2000年1月1日指定为tm_yday = 100,这显然不是真的:

In [72]: time.struct_time((2000,1,1,0,0,0,3,100,-1))
Out[72]: time.struct_time(tm_year=2000, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=100, tm_isdst=-1)

因此,最好使用datetime并调用其timetuple()方法来获取time.struct_time:

In [70]: import datetime as dt

In [71]: dt.datetime(2000,11,30,0,0,0).timetuple()
Out[71]: time.struct_time(tm_year=2000, tm_mon=11, tm_mday=30, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=335, tm_isdst=-1)