time.struct_time 的 structseq() 错误

2024-04-03

这是给出错误的 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)

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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

time.struct_time 的 structseq() 错误 的相关文章

随机推荐