Reputation: 23
I'm having some confusion on some of my code which was previously working (yesterday). Using python 2.7.6
I had
from datetime import datetime
openfor = (datetime.strptime(row[1],"%Y-%m-%d %H:%M:%S") - datetime.strptime(row[2], "%Y-%m-%d %H:%M:%S")).total_seconds()
and it returned the value that is required. As of this morning it is generating
AttributeError: 'module' object has no attribute 'strptime'
If I use the below, with or without the import it works.
openfor = (datetime.datetime.strptime(row[1],"%Y-%m-%d %H:%M:%S") - datetime.datetime.strptime(row[2], "%Y-%m-%d %H:%M:%S")).total_seconds()
It is no real big deal, because it works, but the code looks ugly and my curiosity is piqued. So any suggestions on why this would stop working? And how to resolve? Thanks
Upvotes: 2
Views: 1006
Reputation: 880547
Per the comments, the import statement
from pylab import *
is the cause of the problem. This imports pylab
and copies all the names in the pylab
namespace into the global namespace of the current module. datetime
is one of those names:
In [188]: import pylab
In [189]: 'datetime' in dir(pylab)
Out[189]: True
So datetime
is getting reassigned to the module rather than the class.
Somewhere between
from datetime import datetime
and
openfor = (datetime.strptime(row[1],"%Y-%m-%d %H:%M:%S") - datetime.strptime(row[2], "%Y-%m-%d %H:%M:%S")).total_seconds()
datetime
is getting redefined to equal the module datetime
rather than the class datetime.datetime
.
The cause of this problem is in code that you have not posted.
(But an import statement, import datetime
, is likely the culprit. Also be careful not to use from module import *
, as this could pollute the calling module's namespace with names from the other module. This could include datetime
.)
By the way, some experts recommend never using
from module import function
and instead always importing modules only:
import module # or
import module as foo
While this may be a stylistic choice, adhering to this rule makes it extremely clear where everything is coming from.
Upvotes: 3