gpt4 book ai didi

python strptime 抛出元组索引超出范围

转载 作者:太空宇宙 更新时间:2023-11-03 18:02:26 26 4
gpt4 key购买 nike

使用 Redhat Python 2.7.5 我尝试使用 datetime.datetime.strptime 解析 YYYY-MM-DD 格式的日期,并且间歇性地得到一个元组超出范围错误如下:

client.py in parse_date(d='2014-12-05')
138 return dt.datetime.strptime(d,"%Y-%m-%d")
139 except:
140 raise Exception("Unexpected Date: '{0}' ({1})".format(d), e)
undefined, d = '2014-12-05', e undefined
<type 'exceptions.IndexError'>: tuple index out of range
args = ('tuple index out of range',)
message = 'tuple index out of range'

格式字符串看起来正确,并且问题的间歇性表明存在某种线程问题,但说实话,我不知道,也不知道如何可靠地重现错误。有什么建议可以解决这个问题吗?

最佳答案

我认为问题在于捕获异常的方式:

except:
raise Exception("Unexpected Date: '{0}' ({1})".format(d), e)

在这里,您没有正确地将变量e传递给format。相反,它应该是

except:
raise Exception("Unexpected Date: '{0}' ({1})".format(d, e))

此外,如果 e 恰好引发异常,您将需要显式获取一个变量,如下所示:

except Exception as e:
raise Exception("Unexpected Date: '{0}' ({1})".format(d), e)

最后,最好捕获 try block 可能引发的特定错误,因此您应该这样做

except ValueError as e:
raise Exception("Unexpected Date: '{0}' ({1})".format(d), e)

关于python strptime 抛出元组索引超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27469043/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com