用Python从excel文件中写出无时间的日期

2024-03-28 08:57:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我把它合并成一个csv文件。在

当我在excel文件中阅读时,我有一个日期字段:

0    2018-05-28 00:00:00
1    9999-12-31 00:00:00
2    2018-02-26 00:00:00
3    2018-02-26 00:00:00
4    2018-02-26 00:00:00
Name: Date_started, dtype: object

我检查数据类型

^{pr2}$

然后,当我将结果数据帧写入csv时,我得到了:

df.to_csv(folderpath + "Date_Started_df.csv",encoding="UTF-8" , index=False, na_rep='',date_format='%d%m%Y')
Date_Started

28/05/2018 00:00
31/12/9999 00:00
26/02/2018 00:00
26/02/2018 00:00
26/02/2018 00:00

I have tried

df.loc[:,'Date_Started'] = df['Date_Started'].astype('str').str[8:10] + "/" + 
df['Date_Started'].astype('str').str[5:7] + "/" + 
df['Date_Started'].astype('str').str[:4] 

这给了我:

0    28/05/2018
1    31/12/9999
2    26/02/2018
3    26/02/2018
4    26/02/2018
Name: Date_started, dtype: object

我想可能是写的:

df.to_csv(filename, date_format='%Y%m%d')

但我还有时间!?在


Tags: 文件csvtonameformatdfdateobject
1条回答
网友
1楼 · 发布于 2024-03-28 08:57:27

在发送到CSV之前,您需要将序列转换为datetime

df['Date_Started'] = pd.to_datetime(df['Date_Started'])

这就允许Pandas对带有to_csv的相应列执行date_format='%d%m%Y'to_csv docs使此显式:

date_format : string, default None

Format string for datetime objects

相关问题 更多 >