Python AttributeError: 'module' 对象没有属性 'utcnow'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19192209/
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: 'module' object has no attribute 'utcnow'
提问by user2384994
When I input the simple code:
当我输入简单的代码时:
import datetime
datetime.utcnow()
, I was given error message:
,我收到了错误消息:
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
datetime.utcnow()
AttributeError: 'module' object has no attribute 'utcnow'
But python's document of utcnow
is just here: https://docs.python.org/library/datetime.html#datetime.datetime.utcnow. Why does utcnow
not work in my computer? Thank you!
但是python的文档utcnow
就在这里:https: //docs.python.org/library/datetime.html#datetime.datetime.utcnow。为什么utcnow
在我的电脑上不起作用?谢谢!
采纳答案by Martijn Pieters
You are confusing the module with the type.
您将模块与类型混淆了。
Use either:
使用:
import datetime
datetime.datetime.utcnow()
or use:
或使用:
from datetime import datetime
datetime.utcnow()
e.g. either reference the datetime
type in the datetime
module, or import that type into your namespace from the module. If you use the latter form and need othertypes from that module, don't forget to import those too:
例如,要么引用模块中的datetime
类型,要么将该类型从datetime
模块导入到您的命名空间中。如果您使用后一种形式并需要该模块中的其他类型,请不要忘记导入它们:
from datetime import date, datetime, timedelta
Demo of the first form:
第一种形式的演示:
>>> import datetime
>>> datetime
<module 'datetime' from '/Users/mj/Development/venvs/stackoverflow-2.7/lib/python2.7/lib-dynload/datetime.so'>
>>> datetime.datetime
<type 'datetime.datetime'>
>>> datetime.datetime.utcnow()
datetime.datetime(2013, 10, 4, 23, 27, 14, 678151)