简体   繁体   中英

Unable to use datetime.strptime with from datetime import datetime

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM