Python 将列转换为日期时间
我有这个df:Python 将列转换为日期时间,python,pandas,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 我试图摆脱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的数据类型为
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')
与:
我得到:
AttributeError: 'Series' object has no attribute 'strftime'
我想您需要-输出是字符串
:
#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'>
df['A'].dt.strftime(“%Y-%m-%d”)
怎么样?它是df['A'].dt.strftime(“%Y-%m-%d”)
,但与您的标题相矛盾。您正在尝试转换为datetime还是转换为string?该列的当前dtype
是str还是datetime64?还有,你真正想要的是str还是没有时间的statiledatetime
#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'>
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'>