使用"import dateutil"时出现AttributeError和"dateutil.parser.parse()";但是在使用"from dateutil import parser"时没有问题. [英] AttributeError when using "import dateutil" and "dateutil.parser.parse()" but no problems when using "from dateutil import parser"

查看:305
本文介绍了使用"import dateutil"时出现AttributeError和"dateutil.parser.parse()";但是在使用"from dateutil import parser"时没有问题.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Python 2.7.3中的 dateutil 模块.我只是想使用:

I was playing with the dateutil module in Python 2.7.3. I simply wanted to use:

import dateutil
dateutil.parser.parse("01-02-2013")

但是我遇到了一个错误:

But I got an error:

AttributeError: 'module' object has no attribute 'parser'

我检查了 dateutil 有哪些属性:

I checked what attributes dateutil does have:

print dir(dateutil)
# output: ['__author__', '__builtins__', '__doc__', '__file__', '__license__',
#          '__name__', '__package__', '__path__', '__version__']

问题是,当我尝试直接从 dateutil 导入 parser 时,它确实存在:

The thing is, when I try to import parser from dateutil directly, it does seem to exist:

from dateutil import parser
print parser.parse("01-02-2013")
# output: 2013-01-02 00:00:00

导入解析器中的之后, parser 也神奇地出现在导入的 dateutil 本身中:

After the from dateutil import parser, parser has also magically appeared in the imported dateutil itself:

print dir(dateutil)
# output: ['__author__', '__builtins__', '__doc__', '__file__', '__license__',
#          '__name__', '__package__', '__path__', '__version__', 'parser',
#          'relativedelta', 'tz']

请注意,此列表中仍然缺少其他一些属性(例如 rrule ).

Note that some other attributes (like rrule) are still missing from this list.

任何人都知道发生了什么事吗?

Anyone knows what's going on?

推荐答案

您尚未导入 dateutil.parser .您可以看到它,但是您必须以某种方式导入它.

You haven't imported dateutil.parser. You can see it, but you have to somehow import it.

>>> import dateutil.parser
>>> dateutil.parser.parse("01-02-2013")
datetime.datetime(2013, 1, 2, 0, 0)

这是因为 parser.py dateutil 包中的一个模块.这是文件夹结构中的一个单独文件.

That's because the parser.py is a module in the dateutil package. It's a separate file in the folder structure.

回答您在注释中提出的问题,即从dateutil导入解析器后, relativedelta tz 出现在名称空间中的原因是因为 parser 本身会导入 relativedelta tz .

Answer to the question you asked in the comments, the reason why relativedelta and tz appear in the namespace after you've from dateutil import parser is because parser itself imports relativedelta and tz.

如果查看 dateutil/parser.py 的源代码,则可以看到导入.

If you look at the source code of dateutil/parser.py, you can see the imports.

# -*- coding:iso-8859-1 -*-
"""
Copyright (c) 2003-2007  Gustavo Niemeyer <gustavo@niemeyer.net>

This module offers extensions to the standard Python
datetime module.
"""
... snip ...
from . import relativedelta
from . import tz

这篇关于使用"import dateutil"时出现AttributeError和"dateutil.parser.parse()";但是在使用"from dateutil import parser"时没有问题.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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