gpt4 book ai didi

python - 日期时间到 Pandas 系列的字符串

转载 作者:IT老高 更新时间:2023-10-28 21:50:49 26 4
gpt4 key购买 nike

我应该如何从 datetime 转换为 string?我的尝试:

dates = p.to_datetime(p.Series(['20010101', '20010331']), format = '%Y%m%d')
dates.str

最佳答案

没有.str日期时间的访问器,你不能做 .astype(str)要么。

改为使用 .dt.strftime :

>>> series = pd.Series(['20010101', '20010331'])
>>> dates = pd.to_datetime(series, format='%Y%m%d')
>>> dates.dt.strftime('%Y-%m-%d')
0 2001-01-01
1 2001-03-31
dtype: object

在此处查看有关自定义日期字符串格式的文档:strftime() and strptime() Behavior .


对于旧版 pandas <0.17.0 ,可以改为调用.apply使用 Python 标准库的 datetime.strftime :

>>> dates.apply(lambda x: x.strftime('%Y-%m-%d'))
0 2001-01-01
1 2001-03-31
dtype: object

关于python - 日期时间到 Pandas 系列的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30132282/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com