AttributeError:'模块'对象没有属性'utcnow' [英] AttributeError: 'module' object has no attribute 'utcnow'
问题描述
当我输入简单代码时:
import datetime
datetime.utcnow()
,收到错误消息:
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
datetime.utcnow()
AttributeError: 'module' object has no attribute 'utcnow'
但是 utcnow
的python文档就在这里: https://docs.python.org/library/datetime.html#datetime.datetime.utcnow 。为什么 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!
推荐答案
您正在将模块与类型混淆。
You are confusing the module with the type.
使用以下任一方法:
import datetime
datetime.datetime.utcnow()
或使用:
from datetime import datetime
datetime.utcnow()
例如在 datetime
模块中引用 datetime
类型,或者从该模块将其导入到您的命名空间中。如果您使用后一种形式,并且需要该模块中的 other 类型,请不要忘记也导入这些类型:
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 other types from that module, don't forget to import those too:
from datetime import date, datetime, timedelta
第一种形式的演示
>>> 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)
这篇关于AttributeError:'模块'对象没有属性'utcnow'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!