How to make cell format of 'MMM DD' in xlswriter

Viewed 65

I'm stuck in this problem of formatting a cell to date in xlswriter. The thing is the date is 07/02/2021 and the below image is the result of a manual cell format in excel file which is the correct thing.

enter image description here

While these are the codes I wrote to imitate it.

import xlsxwriter
from datetime import date, datetime

def Test():
    workbook = xlsxwriter.Workbook(path)
    worksheet = workbook.add_worksheet()

    date_string = "2021-07-02"
    datex = datetime.fromisoformat(date_string)
    number = datetime.timestamp(datex)

    formatx = workbook.add_format({'num_format': 'MMM DD'})
    worksheet.write('A1', number, formatx) 

    workbook.close()

But the result is not even close:

enter image description here

I wanted to imitate a format of 'MMM DD' in excel file that if you look at the 'VALUEs BAR' it is '07/02/2021' and if you look at the 'EXCEL ROW DATA' it is 'July 02'.

But the codes I wrote have the result of these:

  • 'VALUEs BAR': '10/22/ -5025'
  • 'EXCEL ROW DATA': 'Oct 22'

When I clearly set the right date in the variable 'date_string'. How can I do this correctly?

1 Answers

The issue is with the line number = datetime.timestamp(datex), remove it:

import xlsxwriter
from datetime import date, datetime

def Test():
    workbook = xlsxwriter.Workbook('test.xlsx')
    worksheet = workbook.add_worksheet()

    date_string = "2021-07-02"
    datex = datetime.fromisoformat(date_string)

    formatx = workbook.add_format({'num_format': 'MMM DD'})
    worksheet.write('A1', datex, formatx) 

    workbook.close()

Output:

xlsx_date

Related