1
votes

I thought I understood about python modules until I tried this

import datetime
datetime.now()

AttributeError Traceback (most recent call last) in ()
1 import datetime

----> 2 datetime.now() AttributeError: 'module' object has no attribute 'now'

from datetime import *
datetime.now()

datetime.datetime(2013, 9, 13, 16, 35, 4, 433977)

from datetime import now

ImportError Traceback (most recent call last) in () ----> 1 from datetime import now ImportError: cannot import name now

My illusion of thinking I knew python modules dissipated immediately. I am using ipython notebook

Thanks

1
import datetime;print datetime.datetime.now()Ashwini Chaudhary
The thing is... I want to do something like from datetime import now, from datetime.datetime import now or from datetime import datetime.nowgota
@NunoCalaim: You could simply create an alias for the function: import datetime; now = datetime.datetime.now - this allows you to just use now().Frerich Raabe

1 Answers

4
votes

There is a class in the datetime module called datetime. This:

import datetime

does not directly import this class: you must reference it with datetime.datetime. datetime alone refers to the datetime module itself. However, this:

from datetime import *

does import the class (along with everything else in the module), which is why you can reference it with simply datetime, not qualified with the module name.

The reason your third snippet does not work is again because you are referencing the datetime module, which does not have a now member. Indeed, now is a part of the datetime class.