OpenPyXl 如何将单元格格式化为日期

OpenPyXl how to format cell as date

我使用 openpyxl 阅读的报告有问题。有时我收到的文件中的单元格格式不正确,我得到的不是“10.03.2020”(单元格格式日期),而是“43900,88455”(单元格格式通用)。

我尝试了 google、openpyxl 文档和 Whosebug,但这并没有让我更接近解决方案。您能否提供帮助并建议如何将单元格格式切换为短日期?

下面没有用,我尝试了很多其他的想法,但还是死胡同。我需要此脚本中其他操作的正确日期。

    def sanitizeDates(self):
        # pass
        for i in range(3, self.fileLength-1):
            self.mainWs.cell(i, 4).number_format = 'dd/mm/yyyy'
            self.mainWs.cell(i, 16).number_format = 'dd/mm/yyyy'

Copy comment: So I have tried

print("Cell (4) type is: " + str(type(self.mainWs.cell(i, 4).value)) + " and current value is " + str(self.mainWs.cell(i, 4).value)) 
print("Cell (16) type is: " + str(type(self.mainWs.cell(i, 16).value)) + " and current value is " + str(self.mainWs.cell(i, 16).value))

that results in Cell (4) type is: <class 'datetime.datetime'> and current value is 2020-03-10 22:41:41
Cell (16) type is: <class 'float'> and current value is 43900.9475
Excel displays it as "General" = "43900,88455"

所以,我终于想通了。 @stovfl 感谢您的提示,这让我想到了要寻找什么以及如何解决我的问题。

Whosebug 上的原始线程可在此处获得:

下面是一个工作代码:

   def sanitizeDates(self):
        for i in range(3, self.fileLength - 1):
            # Check which cells should be sanitized and proceed
            if isinstance(self.mainWs.cell(i, 4).value, float) and isinstance(self.mainWs.cell(i, 16).value, float):
                print(str(self.mainWs.cell(i, 4).value) + " / " + str(self.mainWs.cell(i, 16).value) + " -> " + str(self.convertDate(self.mainWs.cell(i, 4).value)) + " / " + self.convertDate(self.mainWs.cell(i, 16).value))
                self.mainWs.cell(i, 4).value = self.convertDate(self.mainWs.cell(i, 4).value)
                self.mainWs.cell(i, 16).value = self.convertDate(self.mainWs.cell(i, 16).value)
            elif isinstance(self.mainWs.cell(i, 4).value, float):
                print(str(self.mainWs.cell(i, 4).value) + " -> " + str(self.convertDate(self.mainWs.cell(i, 4).value)))
                self.mainWs.cell(i, 4).value = self.convertDate(self.mainWs.cell(i, 4).value)
            elif isinstance(self.mainWs.cell(i, 16).value, float):
                print(str(self.mainWs.cell(i, 16).value) + " -> " + str(self.convertDate(self.mainWs.cell(i, 16).value)))
                self.mainWs.cell(i, 16).value = self.convertDate(self.mainWs.cell(i, 16).value)


    def convertDate(self, dateToConvert):
        # Thank you, Whosebug <3
        # 
        epochStart = datetime(1899, 12, 31)
        if dateToConvert >= 60:
            dateToConvert -= 1  # Excel leap year bug, 1900 is not a leap year
        return epochStart + timedelta(days=dateToConvert)

执行后得到以下结果:

43899.89134259259 -> 2020-03-09 21:23:32

43900.9475 -> 2020-03-10 22:44:24