我正在写一个csv文件。 row [3]和row [4]都是我原始csv文件中的日期列。行[3]和行[4]显示浮动。在csv文件中,它们都是整数,但是当我运行Python代码时,它会显示一个突出显示小数的错误。
import csv
import xlrd
import time
import datetime
workbook = xlrd.open_workbook('T:/SUNDAY REPORT 12.30.16.xlsm')
for sheet in workbook.sheets():
with open('{}.csv'.format(sheet.name), 'wb') as f:
writer = csv.writer(f)
writer.writerows(sheet.row_values(row) for row in range(sheet.nrows))
print "CSV converted"
time.sleep(5)
def xldate_to_datetime(xldate):
tempDate = datetime.datetime(1900, 1, 1)
deltaDays = datetime.timedelta(days=float(xldate)-2)
TheTime = (tempDate + deltaDays )
return TheTime.strftime("%m/%d/%Y")
with open("InfoCenterTracker.csv","rb") as source:
rdr= csv.reader( source )
with open("result.csv","wb") as result:
wtr= csv.writer( result )
next(rdr, None) # skip the headers
for r in rdr:
r[3] = xlrd.xldate.xldate_as_datetime(float(r[3]), workbook.datemode)
r[4] = xlrd.xldate.xldate_as_datetime(float(r[4]), workbook.datemode) if r[1] == "":
pass
else:
wtr.writerow(r[1:19])
print "Columns converted to datetime"
错误:
r[3] = xlrd.xldate.xldate_as_datetime(float(r[3]), workbook.datemode)
ValueError: could not convert string to float:
CSV中的值:
Week(Row[3]): Date(row[4]):
42735.0 42730.0
42735.0 42730.0
42735.0 42731.0
42735.0 42731.0
答案 0 :(得分:1)
这应该与Imran的代码一起发挥作用
r[3] = datetime.datetime.strptime(xldate_to_datetime(r[3]), "%m/%d/%Y")
r[4] = datetime.datetime.strptime(xldate_to_datetime(r[3]), "%m/%d/%Y")
答案 1 :(得分:1)
使用以下函数将excel数字格式转换为datetime对象
def xldate_to_datetime(xldate):
tempDate = datetime.datetime(1900, 1, 1)
deltaDays = datetime.timedelta(days=int(xldate)-2)
TheTime = (tempDate + deltaDays )
return TheTime.strftime("%m/%d/%Y")
然后将date_format更改为
date_format = datetime.datetime.strptime(xldate_to_datetime(r[3:5][0]), "%m/%d/%Y")