问题
I need to write a python script to change from .xlsx file to .csv file: my code :
import xlrd
import csv
def csv_from_excel():
wb = xlrd.open_workbook("Book1.xlsx")
sh = wb.sheet_by_name('Att1FF5.tmp')
your_csv_file = open('your_csv_file.csv', 'wb')
wr = csv.writer(your_csv_file, quoting=csv.QUOTE_ALL)
for rownum in xrange(sh.nrows):
wr.writerow([unicode(entry).encode("utf-8") for entry in sh.row_values(rownum)])
your_csv_file.close()
csv_from_excel()
However , all the date format was changing to integer . for example :
4/13/2018 --> 43203
So is there anyway i can alter my code to keep the date format. My date format is believed to be MM/DD/YYYY
thanks.
回答1:
According to xlrd document, I guess you have to do the conversion yourself, since there is no date type stored in excel.
As the document says, Excel for Windows stores dates by default as the number of days (or fraction thereof) since 1899-12-31T00:00:00. The date of 43203 can be calculated like this:
import datetime, xlrd
xlrd.xldate.xldate_as_tuple(43203, 0) # returns (2018, 4, 13, 0, 0, 0)
xlrd.xldate.xldate_as_datetime(43203, 0) # returns datetime.datetime(2018, 4, 13, 0, 0)
来源:https://stackoverflow.com/questions/47879683/python-xlsx-to-csv-without-change-date-to-interger