Home » excel » Filling an excel file with python is messing up my dates

Filling an excel file with python is messing up my dates

Posted by: admin April 23, 2020 Leave a comment

Questions:

Here is the process,
I have an xlsm file called template, inside a worksheet called data.
Then I have 5 Csv files, I must put the content of all csv file inside the data worksheet.

No problems to do that, except if a date is “07/09/12” it will become “09/07/12” in excel.

So I have a list called data, here is a print of one of it’s line

['07/09/12', 'LARO', 'MEDITERRAN', '245', 'UZES', '11', '0', '0', '0', '0', '11', '0']

I’m putting the in the excel file with this piece of code :

First I open the file (xl is because I use “with self as xl”)

def open(self):
    self.xl.Visible = 1
    self.xl.ScreenUpdating = False
    self.worksheet = self.xl.Workbooks.Open(self.getOutputFile())

Then I erase the data worksheet

def cleanData(self):
    sheet = self.xl.Sheets(self.sheetName)
    def findNumberOfLines(start_line):
        nb = 0
        while sheet.Cells(start_line + nb, self.startColumn).Value is not None:
            nb += 1
        return nb

Then I fill the data

def fillData(self):
    sheet = self.xl.Sheets(self.sheetName)
    noRow = self.startLine
    for row in self.data:
        noCol = self.startColumn
        for i, value in enumerate(row):
            sheet.Cells(noRow, noCol).Value = value
            noCol+=1
        noRow+=1

And I save

def save(self):
    self.worksheet.Save()

And everythong is good except the day and month are inverted inside excel (it’s not displaying US format, it’s displaying EUR format with month and day inverted (3 october becomes 9 march, tested using “long date” format)

Weird thing : the excel cell containing dates is set at “standard” but once it has been filed by my python script it’s set at “date”

WORKAROUND
when filling the sheet I’m intercepting every date and converting them
to datetime, excel seems to like that

def fillData(self):
    sheet = self.xl.Sheets(self.sheetName)
    noRow = self.startLine
    pattern = re.compile('^\d+/\d+/\d+$')
    for row in self.data:
        noCol = self.startColumn
        for i, value in enumerate(row):

            if (pattern.match(str(value))):
                date = value.rsplit('/')
                sheet.Cells(noRow, noCol).Value = datetime(int(date[2]), int(date[1]), int(date[0]))
            else: sheet.Cells(noRow, noCol).Value = value
            noCol+=1
        noRow+=1
How to&Answers:

Unless you tell Excel, it tries to be “smart” with dates which means it will guess what the format is and how to display the converted date.

In almost all cases, you don’t want that. Such files will display differently on computers with different date formats or when users have changed the OS default (even some Americans prefer DD/MM/YY over the standard MM/DD/YY).

So the correct solution is to datetime instead of string values. This works, btw. because the COM framework inside of win32com will convert the Python datetime object to the corresponding Excel date object plus set the formatting correctly.