很难用Python导入我的头脑。我已经阅读了导入X和X import * here- http://effbot.org/zone/import-confusion.htm之间的区别,但是我很难理解导入“模块”和“模块”导入*之间的区别。特别是因为effbot文章建议坚持导入“模块”,而这在这里不起作用。
此代码
import csv
import time
import datetime
startdate = time.strptime('31-Dec-50', "%d-%b-%y")
enddate = time.strptime('1-Jan-00', "%d-%b-%y")
with open('Classroom Utilization.csv', 'rb') as csvfile:
file = csv.DictReader(csvfile, delimiter=',')
for row in file:
checkstartdate = time.strptime(row['startdate'], "%d-%b-%y")
checkenddate = time.strptime(row['enddate'], "%d-%b-%y")
if checkstartdate < startdate:
startdate = checkstartdate
if checkenddate > enddate:
enddate = checkenddate
print time.strftime("%d-%b-%y", startdate)
print time.strftime("%d-%b-%y", enddate)
print "pre convert: " + str(startdate)
print "pre convert: " + str(enddate)
startdate = datetime.fromtimestamp(mktime(startdate))
enddate = datetime.fromtimestamp(mktime(enddate))
print "post convert: " + str(startdate)
print "post convert: " + str(enddate)
print '%s/%s/%s' % (startdate.month, startdate.day , startdate.year)
返回此错误
File "deconflict.py", line 29, in <module>
startdate = datetime.fromtimestamp(mktime(startdate))
AttributeError: 'module' object has no attribute 'fromtimestamp'
在文档(https://docs.python.org/2/library/datetime.html?highlight=datetime#module-datetime)中,datetime模块中的datetime对象具有fromtimestamp的方法,但导入不允许我使用它。
另一方面,使用模块导入*修复了所有问题。虽然我不明白为什么从时间导入*允许我只使用strptime(),但从datetime import *我仍然要说datetime.fromtimestamp。
import csv
from time import *
from datetime import *
startdate = strptime('31-Dec-50', "%d-%b-%y")
enddate = strptime('1-Jan-00', "%d-%b-%y")
with open('Classroom Utilization.csv', 'rb') as csvfile:
file = csv.DictReader(csvfile, delimiter=',')
for row in file:
checkstartdate = strptime(row['startdate'], "%d-%b-%y")
checkenddate = strptime(row['enddate'], "%d-%b-%y")
if checkstartdate < startdate:
startdate = checkstartdate
if checkenddate > enddate:
enddate = checkenddate
print strftime("%d-%b-%y", startdate)
print strftime("%d-%b-%y", enddate)
print "pre convert: " + str(startdate)
print "pre convert: " + str(enddate)
startdate = datetime.fromtimestamp(mktime(startdate))
enddate = datetime.fromtimestamp(mktime(enddate))
print "post convert: " + str(startdate)
print "post convert: " + str(enddate)
print '%s/%s/%s' % (startdate.month, startdate.day , startdate.year)
答案 0 :(得分:2)
在这种特定情况下,datetime
模块具有datetime
类。这很令人困惑,因为它们具有相同的名称。当您执行import datetime
时,您获得的是名为datetime
的模块。要访问该模块的成员(例如datetime
类),您需要完全限定它(例如:datetime.datetime
)
例如:
import datetime
startdate = datetime.datetime.fromtimestamp(mktime(startdate))
执行from datetime import *
时,datetime
引用的内容不是模块,而是同名的类。您得到的对象与from datetime import datetime
相同,即“从日期时间模块导入日期时间类”
答案 1 :(得分:1)
datetime模块中有一个datetime类。这就是你如何使用它
from datetime import datetime
datetime.fromtimestamp
或
JSONCollection
时间模块没有时间类并直接公开其方法。