简体   繁体   English

strptime 不更改 Excel 中的日期格式

[英]strptime not changing date fomat in Excel

I am reading a table and writing to CSV.我正在阅读表格并写入 CSV。 I have some columns where I want to change the date format.我有一些列要更改日期格式。 Below is some code I have下面是我的一些代码

    for row in out[1]:
        dt = datetime.datetime.strptime(row[18], '%Y-%m-%d %H:%M:%S.%f')
        row[18] = dt.strftime('%Y-%m-%d)
        print(row[18])

It does seem to change the date format to what I'm looking for because the print statement shows as much, but when I open the excel sheet that it wrote, the date format is like 11/12/2019 instead of 2020-11-12.它似乎确实将日期格式更改为我正在寻找的内容,因为打印语句显示的内容一样多,但是当我打开它编写的 excel 表时,日期格式就像 11/12/2019 而不是 2020-11- 12.

Any advice?有什么建议吗? I'm trying to prevent manually changing the format date once opening excel我试图阻止打开 excel 后手动更改格式日期

Most likely, what Excel shows you is not what the underlying data is.最有可能的是,Excel 向您显示的不是基础数据。 Excel auto formats fields when it displays them. Excel 在显示字段时自动格式化字段。 Hence, if it opens a CSV and sees 2020-11-12 it will recognize it is a date and display it for you as a formatted date field.因此,如果它打开 CSV 并看到 2020-11-12 它将识别它是一个日期并将其显示为格式化的日期字段。 If you want to save a field as TEXT that Excel will know is TEXT, then the cell has to start with a " ' ".如果要将字段保存为 Excel 知道的 TEXT 字段,则单元格必须以“'”开头。 Try adding this:尝试添加这个:

row[18] = dt.strftime('\'%Y-%m-%d')

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

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