熊猫将列转换为日期时间

war*_*nry 4 python pandas

我有这个 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
Run Code Online (Sandbox Code Playgroud)

我试图摆脱 H、M、S,这样我就剩下:

     A
0   2017-04-17
1   2017-04-18 
2   2017-04-19 
3   2017-04-20 
4   2017-04-21 
Run Code Online (Sandbox Code Playgroud)

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

df['A'] = df['A']datetime.strftime('%Y-%m-%d')
Run Code Online (Sandbox Code Playgroud)

和:

import datetime as datetime
Run Code Online (Sandbox Code Playgroud)

我得到:

AttributeError: 'Series' object has no attribute 'strftime'
Run Code Online (Sandbox Code Playgroud)

jez*_*ael 5

我认为你需要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'>
Run Code Online (Sandbox Code Playgroud)

和日期使用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'>
Run Code Online (Sandbox Code Playgroud)