开发者

Strange Python datetime import problem

Hi I'm finding this problem to manifest differently on various setups. I've had any one of the following work while the others fail, and this changes sometimes (that is one snippet would fail on one setup while the other fail on another)

from datetime import datetime
datetime.datetime.utcnow()


import datetime
datetime.datetime.utcnow()

For example, I've just upgraded to python 2.7 from 2.6 and the first snippet which worked fine before now errors

Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: type object 'datetime.datetime' has no attribute 'datetime'

which is fine, but the same snippet wo开发者_StackOverflow中文版rked in 2.6, while the second snippet failed. Now its reversed...

This is quite a weird problem...

Thanks Harel


The other answers here are correct (your import is wrong), but here's a snippet that will make it more clear what's happening when you do that.

>>> import datetime
>>> type(datetime)
<class 'module'>
>>> type(datetime.datetime)
<class 'type'>
>>> from datetime import datetime
>>> type(datetime)
<class 'type'>


IF you're doing from datetime import datetime, you need to use datetime.utcnow() instead of datetime.datetime.utcnow(). I can't possibly see how your first snippet could ever work.

>>> from datetime import datetime
>>> datetime.datetime.utcnow()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
>>> datetime.utcnow()
datetime.datetime(2011, 5, 3, 14, 10, 36, 30592)


You are mistaken. The first snippet is incorrect in both versions.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜