難以置信地圍繞着Python導入。我已經讀過了導入X和X導入*這裏的區別 - http://effbot.org/zone/import-confusion.htm,但我很難理解導入「模塊」和「模塊」導入*之間的區別。特別是因爲effbot文章建議堅持使用導入「模塊」,這在這裏不起作用。Python導入解釋
此代碼
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模塊的日期時間對象有方法fromtimestamp,但進口並沒有讓我用它。
另一方面,使用從模塊導入*修復所有問題。雖然我不明白爲什麼從時間導入*允許我只使用strptime(),但從datetime導入*我仍然必須說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)