使用 dateutil 解析日期时出现问题 [英] Trouble in parsing date using dateutil

查看:53
本文介绍了使用 dateutil 解析日期时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 python-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

我期望 dateutil.parser.parse('some null string', Fuzzy=True).date() 抛出异常,但它返回当前日期.如果在提供的字符串中找不到日期,有人可以告诉我如何避免获取当前日期吗?

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?

提前致谢.

推荐答案

请参阅 dateutil 文档,特别是解析函数(强调我的):

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

此外,以下关键字参数可用:

Additionally, the following keyword arguments are available:

默认如果给定,这必须是一个日期时间实例.解析日期中缺少的任何字段都将从该实例中复制.默认值为当前日期,00:00:00am.

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.

...(剪辑)...

模糊如果模糊设置为 True,则字符串中的未知标记将被忽略.

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

鉴于您已将 fuzzy 设置为 True,不会抛出异常,因为它会简单地忽略所有未知标记.并且,由于未传递 default 参数,将返回当前日期.

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.

所以解决方案要么保持fuzzy设置为False,这样无效的格式字符串就会抛出异常;或检查返回的日期时间是否等于上午 00:00:00 的当前日期作为转换失败的指示.

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.

这篇关于使用 dateutil 解析日期时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆