简体   繁体   English

如何使用 python 将 excel 文件中的日期转换为文本格式

[英]How to convert a date to text format in excel file using python

Excel store date Column call Today and data type is date Excel 存储日期列调用今天,数据类型为日期

Today今天
13/12/2021 2021 年 13 月 12 日
14/12/2021 2021 年 14 月 12 日
15/12/2021 2021 年 15 月 12 日

when i import the excel to another excel using python, how to change the date type to text type?当我使用 python 将 excel 导入另一个 excel 时,如何将日期类型更改为文本类型?

below is my code and try to convert, but not work.下面是我的代码并尝试转换,但不起作用。 could anyone give me advise?谁能给我建议? thanks谢谢

data.insert(0, {'Date':datetime.strptime(str(Today),'%d/%m/%Y').strftime('%d/%m/%Y')})

Excel try to recognize date format even if you cast your column Today as string. Excel 尝试识别日期格式,即使您将Today的列转换为字符串。

Suppose the following dataframe:假设如下 dataframe:

df = pd.DataFrame({'ID': [123, 456, 789], 'Name': ['Louis', 'Paul', 'Alexandre'],
                   'Today': pd.date_range('2021-12-14', periods=3, freq='D')})
print(df)

# Output:
    ID       Name      Today
0  123      Louis 2021-12-14
1  456       Paul 2021-12-15
2  789  Alexandre 2021-12-16

If you export your dataframe with df.to_excel('data.xlsx', index=False) , you got:如果您使用df.to_excel('data.xlsx', index=False)导出 dataframe ,您会得到:

在此处输入图像描述

Here, the trick:这里,诀窍:

with pd.ExcelWriter('data.xlsx') as writer:
    df.to_excel(writer, index=False)
    wb = writer.book
    ws = wb.active
    # For the third column only (Today, Col C)
    for col in ws.iter_cols(min_col=3, max_col=3):
        # For all rows below header (C2, C3, C4, ...)
        for cell in col[1:]:
            cell.number_format = 'DD/MM/YYYY'

Now, you got:现在,你得到了:

在此处输入图像描述

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

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