简体   繁体   English

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

[英]OpenPyXl how to format cell as date

I have a problem with a report I am reading with openpyxl.我正在使用 openpyxl 阅读报告时遇到问题。 Sometimes cell formats in a file I receive are not correct, and instead of "10.03.2020" (cell format Date) I get "43900,88455" (cell format General).有时我收到的文件中的单元格格式不正确,而不是“10.03.2020”(单元格格式日期),我得到“43900,88455”(单元格格式常规)。

I tried google, openpyxl documentation and StackOverflow but that did not bring me any closer to the solution.我尝试了 google、openpyxl 文档和 StackOverflow,但这并没有让我更接近解决方案。 Would you be able to help and advise how to switch cell format to Short Date, please?请问您能否帮助并建议如何将单元格格式切换为短日期?

Below did not work, I tried many other ideas but still in a dead end.下面不起作用,我尝试了许多其他想法,但仍处于死胡同。 I need correct dates for other operations within this script.我需要此脚本中其他操作的正确日期。

    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导致单元格 (4) 类型为: <class 'datetime.datetime'>并且当前值为2020-03-10 22:41:41
Cell (16) type is: <class 'float'> and current value is 43900.9475单元格 (16) 类型为: <class 'float'> ,当前值为43900.9475
Excel displays it as "General" = "43900,88455" Excel 将其显示为"General" = "43900,88455"

So, I have figured this out after all.所以,我毕竟想通了这一点。 @stovfl thanks for your hints, this brought me to an idea what to look for and as a result, how to solve my issue. @stovfl 感谢您的提示,这让我想到了要查找的内容以及如何解决我的问题。

Original thread on StackOverflow is available here: https://stackoverflow.com/a/29387450/5210159 StackOverflow 上的原始线程可在此处获得: https://stackoverflow.com/a/29387450/5210159 : https://stackoverflow.com/a/29387450/5210159

Below is a working code:下面是一个工作代码:

   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, StackOverflow <3
        # https://stackoverflow.com/questions/29387137/how-to-convert-a-given-ordinal-number-from-excel-to-a-date
        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)

After execution I get following results:执行后我得到以下结果:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM