日期时间与 pandas 系列中的字符串 [英] datetime to string with series in pandas
本文介绍了日期时间与 pandas 系列中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要让这件事变得简单:
I need to make this simple thing:
dates = p.to_datetime(p.Series(['20010101', '20010331']), format = '%Y%m%d')
dates.str
但是我得到一个错误.我应该如何从 datetime
转换为 string
?
But I get an error. How should I transform from datetime
to string
?
推荐答案
日期时间没有 str
访问器,你不能做 dates.astype(str)
或者,您可以调用 apply
并使用 datetime.strftime
:
There is no str
accessor for datetimes and you can't do dates.astype(str)
either, you can call apply
and use datetime.strftime
:
In [73]:
dates = pd.to_datetime(pd.Series(['20010101', '20010331']), format = '%Y%m%d')
dates.apply(lambda x: x.strftime('%Y-%m-%d'))
Out[73]:
0 2001-01-01
1 2001-03-31
dtype: object
您可以使用任何您喜欢的方式更改日期字符串的格式:strftime() 和 strptime() 行为.
You can change the format of your date strings using whatever you like: strftime() and strptime() Behavior.
更新
从 0.17.0
版本开始,您可以使用 dt.strftime
As of version 0.17.0
you can do this using dt.strftime
dates.dt.strftime('%Y-%m-%d')
现在可以工作了
这篇关于日期时间与 pandas 系列中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文