Python 使用“import dateutil”和“dateutil.parser.parse()”时出现 AttributeError 但使用“from dateutil import parser”时没有问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23385003/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
AttributeError when using "import dateutil" and "dateutil.parser.parse()" but no problems when using "from dateutil import parser"
提问by Stefan van den Akker
I was playing with the dateutil
modulein Python 2.7.3. I simply wanted to use:
我正在玩Python 2.7.3 中的dateutil
模块。我只是想使用:
import dateutil
dateutil.parser.parse("01-02-2013")
But I got an error:
但我得到了一个错误:
AttributeError: 'module' object has no attribute 'parser'
I checked what attributes dateutil
doeshave:
我查了一下属性dateutil
确实具有:
print dir(dateutil)
# output: ['__author__', '__builtins__', '__doc__', '__file__', '__license__',
# '__name__', '__package__', '__path__', '__version__']
The thing is, when I try to import parser
from dateutil
directly, it does seem to exist:
问题是,当我尝试直接导入parser
时dateutil
,它似乎确实存在:
from dateutil import parser
print parser.parse("01-02-2013")
# output: 2013-01-02 00:00:00
After the from dateutil import parser
, parser
has also magically appeared in the imported dateutil
itself:
之后from dateutil import parser
,parser
也神奇地出现在了 importdateutil
本身中:
print dir(dateutil)
# output: ['__author__', '__builtins__', '__doc__', '__file__', '__license__',
# '__name__', '__package__', '__path__', '__version__', 'parser',
# 'relativedelta', 'tz']
Note that some other attributes (like rrule
) are still missing from this list.
请注意,rrule
此列表中仍缺少一些其他属性(如)。
Anyone knows what's going on?
有谁知道发生了什么?
采纳答案by msvalkon
You haven't imported dateutil.parser
. You can see it, but you haveto somehow import it.
您尚未导入dateutil.parser
. 你可以看到它,但你必须以某种方式导入它。
>>> import dateutil.parser
>>> dateutil.parser.parse("01-02-2013")
datetime.datetime(2013, 1, 2, 0, 0)
That's because the parser.py
is a module in the dateutil
package. It's a separate file in the folder structure.
那是因为parser.py
是dateutil
包中的一个模块。它是文件夹结构中的一个单独文件。
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
.
回答您在评论中提出的问题,为什么relativedelta
和tz
出现在您之后的命名空间中from dateutil import parser
是因为parser
它本身导入了relativedelta
和tz
。
If you look at the source code of dateutil/parser.py
, you can see the imports.
如果您查看 的源代码dateutil/parser.py
,您可以看到导入。
# -*- coding:iso-8859-1 -*-
"""
Copyright (c) 2003-2007 Gustavo Niemeyer <[email protected]>
This module offers extensions to the standard Python
datetime module.
"""
... snip ...
from . import relativedelta
from . import tz