Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

python - Trouble in parsing date using dateutil

I am using python-dateutil for parsing a date from a string:

import dateutil.parser
print dateutil.parser.parse('some null string', fuzzy=True).date()
2012-10-18
print dateutil.parser.parse('some 31 Oct 2012 string', fuzzy=True).date()
2012-10-31

What I am expecting is for dateutil.parser.parse('some null string', fuzzy=True).date() to throw an exception, but it's returning the current date. Can someone show me how I can avoid getting the current date, if no date is found in the provided string?

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

See the dateutil docs, specifically the parse function (emphasizes mine):

Additionally, the following keyword arguments are available:

default If given, this must be a datetime instance. Any fields missing in the parsed date will be copied from this instance. The default value is the current date, at 00:00:00am.

... (snip) ...

fuzzy If fuzzy is set to True, unknown tokens in the string will be ignored.

Given that you've set fuzzy to True, no exception will be thrown as it will simply ignore all unknown tokens. And, as the default argument is not passed, the current date will be returned.

So the solution will be to either keep fuzzy set to False, so that invalid format strings will throw an exception; or check if the returned datetime is equal to the current date at 00:00:00am as an indication of a failed conversion.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...