pandas 熊猫将列转换为日期时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43676152/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 03:30:01 来源:igfitidea点击:
Pandas convert column to datetime
提问by warrenfitzhenry
I have this df:
我有这个 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
I am trying to get rid of the H, M, S, so that I am left with:
我试图摆脱 H、M、S,这样我就剩下:
A
0 2017-04-17
1 2017-04-18
2 2017-04-19
3 2017-04-20
4 2017-04-21
the dtype of column A is object. I have tried:
A列的数据类型是对象。我试过了:
df['A'] = df['A']datetime.strftime('%Y-%m-%d')
with:
和:
import datetime as datetime
I get:
我得到:
AttributeError: 'Series' object has no attribute 'strftime'
采纳答案by jezrael
I think you need dt.strftime
- output are strings
:
我认为你需要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'>
and for dates use date
:
和日期使用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'>