【发布时间】:2016-11-04 00:20:15
【问题描述】:
将datetime.strptime() 格式字符串和日期字符串参数混用是很常见的错误:
datetime.strptime("%B %d, %Y", "January 8, 2014")
而不是相反:
datetime.strptime("January 8, 2014", "%B %d, %Y")
当然,它会在运行时失败:
>>> datetime.strptime("%B %d, %Y", "January 8, 2014")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_strptime.py", line 325, in _strptime
(data_string, format))
ValueError: time data '%B %d, %Y' does not match format 'January 8, 2014'
但是,是否有可能在实际运行代码之前静态地捕捉到这个问题? pylint 或 flake8 可以帮忙吗?
我已经尝试过 PyCharm 代码检查,但两个 sn-ps 都没有发出任何警告。可能是因为两个参数具有相同的类型——它们都是字符串,这使得问题变得更加困难。我们必须实际分析一个字符串是否为日期时间格式字符串。此外,Language Injections PyCharm/IDEA 功能看起来很相关。
【问题讨论】:
-
alecxe,通常如果我们想将字符串转换为日期时间,我们会在特定字符串上使用 strptime(),除了 strptime,如果给定的字符串是正确的日期时间格式,我们可以使用正则表达式检查字符串与否,但需要更多的正则表达式模式来检查。
标签: python datetime pycharm pylint static-code-analysis