尽管修改了parseinfo.JUMP属性,但Dateutil将字符串解析为日期错误
我正在创建一个函数来检测某个值是否是一个日期(给定了各种不同的格式)。dateutil.parser.parse在这方面做得很好,但它错误地将我的一些数据识别为日期。
具体来说,它正在将'ad- 3‘更正为datetime.datetime(2019年、10、3、0、0),这是当前月份和年份的第3次。
我试过修改parseinfo以排除‘广告’
根据dateutil的文档,解析命令采用parseinfo参数。
我认为我的问题是因为传递给解析的默认parseinfo类在其跳转属性中包含'ad‘。我尝试实例化自己的parseinfo类,修改跳转列表属性并将其传递给解析,但问题仍然存在。
from dateutil import parser
def check_format(val, pi = parser.parserinfo()):
# Check date
try:
parser.parse(val, parserinfo=pi)
return 'date'
except ValueError:
return 'Not date'
default_pi = parser.parserinfo()
my_pi = parser.parserinfo()
my_pi.JUMP = [j for j in my_pi.JUMP if j not in ['ad']]
print('Default JUMP List:')
print(default_pi.JUMP) # Print the default JUMP list and you can se ad is part of the list
print('My Corrected JUMP List')
print(my_pi.JUMP) # Print the modified JUMP list and you see that we have successfully excluded
print('Return using default JUMP list:')
print(check_format('ad-3')) # Using default parserinfo
print('Return using my JUMP list:')
print(check_format('ad-3', my_pi)) # Using my parserinfo
print('Control test with a normal string:')
print(check_format('sad-3', my_pi))问题:
check_format('ad-3', my_pi)返回'date‘,尽管传递了parserinfo实例,该实例将'ad’排除在其列表之外。
作为一个控件,我传递了一个类似的字符串'sad-3‘,输出就像预期的那样:'Not date’。
输出:
默认跳转列表:“”、“.”、“/”、“at”、“on”、“on”、“ad”、“m”、“t”、“of”、“st”、“nd”、“rd”、“th”
我更正的跳转列表‘','.','/',','at','on',’on ','m','t','of','st','nd','rd','th‘
使用默认跳转列表返回:日期
使用跳转列表返回:日期
使用普通字符串的控件测试: Not
发布于 2020-09-11 12:48:17
我在谷歌其他东西,但无意中发现你的问题,所以我会回答它。
PI和其他是类属性。您只需要按照正确的顺序实例化它。
from dateutil import parser
def check_format(val, pi):
# Check date
try:
parser.parse(val, parserinfo=pi())
return 'date'
except ValueError:
return 'Not date'
default_pi = parser.parserinfo
my_pi = parser.parserinfo
my_pi.JUMP = [j for j in my_pi.JUMP if j not in ['ad']]
print('Default JUMP List:')
print(default_pi.JUMP) # Print the default JUMP list and you can se ad is part of the list
print('My Corrected JUMP List')
print(my_pi.JUMP) # Print the modified JUMP list and you see that we have successfully excluded
print('Return using default JUMP list:')
print(check_format('ad-3', default_pi)) # Using default parserinfo
print('Return using my JUMP list:')
print(check_format('ad-3', my_pi)) # Using my parserinfo
print('Control test with a normal string:')
print(check_format('sad-3', my_pi))check_format('ad-3',my_pi)返回'date‘,尽管传递了一个parserinfo实例,将'ad’排除在其列表之外。
现在它返回Not date。
https://stackoverflow.com/questions/58442671
复制相似问题