Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 worked in 2.6, while the second snippet failed. Now its reversed...

This is quite a weird problem...

Thanks Harel

like image 852
Harel Avatar asked Feb 24 '23 08:02

Harel


2 Answers

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'>
like image 170
Daenyth Avatar answered Feb 26 '23 20:02

Daenyth


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)
like image 29
Chinmay Kanchi Avatar answered Feb 26 '23 20:02

Chinmay Kanchi