Skip to main content
 首页 » 编程设计

python之Pandas 将列转换为日期时间

2024年10月01日9shangdawei

我有这个 df:

    A 
0   2017-04-17 00:00:00 
1   2017-04-18 00:00:00 
2   2017-04-19 00:00:00 
3   2017-04-20 00:00:00 
4   2017-04-21 00:00:00 

我试图去掉 H、M、S,这样我就剩下:

     A 
0   2017-04-17 
1   2017-04-18  
2   2017-04-19  
3   2017-04-20  
4   2017-04-21  

A 列的数据类型是对象。我试过:

df['A'] = df['A']datetime.strftime('%Y-%m-%d') 

与:

import datetime as datetime 

我得到:

AttributeError: 'Series' object has no attribute 'strftime' 

请您参考如下方法:

我想你需要dt.strftime - 输出是 strings:

#if necessary 
#df['A'] = pd.to_datetime(df['A']) 
 
print (type(df.loc[0, 'A'])) 
<class 'pandas.tslib.Timestamp'> 
 
df['A'] = df['A'].dt.strftime('%Y-%m-%d') 
print (df) 
            A 
0  2017-04-17 
1  2017-04-18 
2  2017-04-19 
3  2017-04-20 
4  2017-04-21 
 
print (type(df.loc[0, 'A'])) 
<class 'str'> 

对于日期使用 date :

df['A'] = df['A'].dt.date 
print (df) 
 
            A 
0  2017-04-17 
1  2017-04-18 
2  2017-04-19 
3  2017-04-20 
4  2017-04-21 
 
print (type(df.loc[0, 'A'])) 
<class 'datetime.date'>