gpt4 book ai didi

python - python中的字符串日期转换

转载 作者:太空宇宙 更新时间:2023-11-04 04:25:40 24 4
gpt4 key购买 nike

我有一个日期格式为“Mar-97”的数据框,我想将其转换为“03-1997”。数据格式为

     Month  SilverPrice GoldPrice
0 Mar-97 186.48 12619.24
1 Apr-97 170.65 12338.59
2 May-97 170.44 12314.94
3 Jun-97 169.96 12202.78
4 Jul-97 155.80 11582.07

我写了这段代码,但它正在将它转换成“1997-03-01”

from datetime import datetime
df["Month"]=list(map(lambda x:datetime.strptime(x,'%b-%y'),df["Month"]))

输出是这样的

      Month SilverPrice GoldPrice
0 1997-03-01 186.48 12619.24
1 1997-04-01 170.65 12338.59
2 1997-05-01 170.44 12314.94
3 1997-06-01 169.96 12202.78
4 1997-07-01 155.80 11582.07

我可以通过剥离日值来做到这一点,但有什么直接的方法可以将其转换为“MM-YYYY”格式。

最佳答案

pd.Series.dt.strftime

您可以通过 Python 的 strftime directives 指定您的 datetime 格式:

df['Month'] = pd.to_datetime(df['Month']).dt.strftime('%m-%Y')

print(df)

Month SilverPrice GoldPrice
0 03-1997 186.48 12619.24
1 04-1997 170.65 12338.59
2 05-1997 170.44 12314.94
3 06-1997 169.96 12202.78
4 07-1997 155.80 11582.07

关于python - python中的字符串日期转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53561162/

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