pythonexcelopenpyxl

How to get the actual value of a cell with openpyxl


I'm trying to get values from an excel sheet however there is a column filled with dates.

Image of that column

I want to get the value exactly how it is in the cell(22-Nov-21) but instead I'm getting the value as 2021-11-22 00:00:00


Solution

  • Openpyxl doesn't evaluate the cell contents or formatting on it's own, as it doesn't actually run Excel, just accesses the file. Therefore, when you get the cell value, you are getting the datetime object it contains, not the displayed format you see when opening Excel. You could do as @Gedas suggested and get the cell format using cell.number_format and try and format based on that. But it's easier to just do as @Charlie recommended and format yourself (see the documentation for datetime for more information on formatting and format codes).

    import openpyxl as op
    import datetime as dt
    
    wb = op.load_workbook("Date_format.xlsx")
    ws = wb["Sheet1"]
    
    your_date = ws.cell(row=1, column=1).value
    your_formatted_date = your_date.strftime("%d-%b-%y")
    print(your_formatted_date)
    
    >>>
    22-Nov-21