简体   繁体   English

将整数(使用xlrd读取)转换回日期格式(使用openpyxl写入)

[英]Convert an integer (read with xlrd) back into a date format (write using openpyxl)

I'm using xlrd to read some dates in a file, an writing them in a new workbook using openpyxl. 我正在使用xlrd读取文件中的某些日期,使用openpyxl将它们写入新工作簿。

If the date is 25-jun-14, it writes 41815 如果日期是25-jun-14,则写入41815

I just want to know how to turn 41815 back into 25-jun-14 again, or 25/06/14 however all the material I've read today seems extremely overcomplicated. 我只是想知道如何将41815再次变回25-jun-14,或25/06/14但是我今天阅读的所有材料看起来都非常复杂。

I suppose value of originReport.cell_value(0,0) is '25-jun-14' . 我认为originReport.cell_value(0,0)值是'25-jun-14'

from datetime import datetime
import re

a = '25-jun-14'
b = re.sub('-14', '-2014', a)

c = datetime.strptime(b, "%d-%b-%Y")

# write 25/06/2014
destReport.cell(row=1,column=1).value = c.strftime("%d/%m/%Y")

I think you should write 2014 instead of 14. Otherwise, how can you tell which stands for year. 我认为你应该写2014而不是14。否则,你怎么知道哪一年代表什么。

With openpyxl you could modify the file in place. 使用openpyxl,您可以修改文件。

Nevertheless the conversion is pretty easy: Excel treats are numbers (with 1900-01-01 as the epoch) that are formatted as dates so you simply need to set the format of the cell. 然而,转换非常简单:Excel处理的是数字(以1900-01-01作为时期),格式化为日期,因此您只需设置单元格的格式。

originReport = xlrd.open_workbook('report1').sheet_by_index(0)
destReport = openpyxl.load_workbook('report2')[0]
c = destReport.cell(row=1,column=1)
c.value = originReport.cell_value(0,0)
c.number_format = "d-mmm-yy" # Excel's formatting
# check the conversion
print(c.value)
2014-06-25 00:00:00

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM