Skip to main content
 首页 » 编程设计

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

2024年12月31日20Leo_wl

我有一个日期格式为“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