gota
gota

Reputation: 2659

Can you explain why I have this?

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

Upvotes: 1

Views: 219

Answers (1)

arshajii
arshajii

Reputation: 129507

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.

Upvotes: 4

Related Questions