Python xlsx to csv without change date to interger

痴心易碎 提交于 2019-12-24 20:22:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!