Search code examples
pythonxlrdopenpyxl

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.

If the date is 25-jun-14, it writes 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.


Solution

  • With openpyxl you could modify the file in place.

    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.

    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