Python 将 Pandas DataFrame 中的日期对象列转换为字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19738169/
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-08-19 14:29:02  来源:igfitidea点击:

Convert column of date objects in Pandas DataFrame to strings

pythondatetimepandas

提问by user2333196

How to convert a column consisting of datetime64 objects to a strings that would read 01-11-2013 for today's date of November 1.

如何将包含 datetime64 对象的列转换为今天的 11 月 1 日日期为 01-11-2013 的字符串。

I have tried

我试过了

df['DateStr'] = df['DateObj'].strftime('%d%m%Y')

but I get this error

但我收到这个错误

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

AttributeError: 'Series' 对象没有属性 'strftime'

采纳答案by Jeff

In [6]: df = DataFrame(dict(A = date_range('20130101',periods=10)))

In [7]: df
Out[7]: 
                    A
0 2013-01-01 00:00:00
1 2013-01-02 00:00:00
2 2013-01-03 00:00:00
3 2013-01-04 00:00:00
4 2013-01-05 00:00:00
5 2013-01-06 00:00:00
6 2013-01-07 00:00:00
7 2013-01-08 00:00:00
8 2013-01-09 00:00:00
9 2013-01-10 00:00:00

In [8]: df['A'].apply(lambda x: x.strftime('%d%m%Y'))
Out[8]: 
0    01012013
1    02012013
2    03012013
3    04012013
4    05012013
5    06012013
6    07012013
7    08012013
8    09012013
9    10012013
Name: A, dtype: object

回答by Kamil Sindi

As of version 17.0, you can format with the dtaccessor:

version 17.0 开始,您可以使用dt访问器进行格式化:

df['DateStr'] = df['DateObj'].dt.strftime('%d%m%Y')