python xlsx到csv无需更改日期就可以整数 [英] Python xlsx to csv without change date to interger
问题描述
我需要编写一个python脚本,以将.xlsx文件更改为.csv文件: 我的代码:
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()
但是,所有日期格式都已更改为integer.例如:
However , all the date format was changing to integer . for example :
4/13/2018-> 43203
4/13/2018 --> 43203
所以无论如何我都可以更改代码以保留日期格式.我的日期格式被认为是MM/DD/YYYY
So is there anyway i can alter my code to keep the date format. My date format is believed to be MM/DD/YYYY
谢谢.
推荐答案
根据 xlrd文档,我想您必须自己进行转换,因为excel中没有存储日期类型.
According to xlrd document, I guess you have to do the conversion yourself, since there is no date type stored in excel.
如文档所述,Excel for Windows stores dates by default as the number of days (or fraction thereof) since 1899-12-31T00:00:00
. 43203
的日期可以这样计算:
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)
这篇关于python xlsx到csv无需更改日期就可以整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!