首页 > 解决方案 > python - 如何在python中将日期时间格式Year-Quarter转换为Quarter-Year?

问题描述

现在我在 pandas 数据框中有这样的列:

Year_Quarter
2014Q1
2015Q1
2015Q2
2016Q3

我通过使用以下代码转换另一列日期来获得此列:

combine['Publish Date'] = pd.to_datetime(combine['Publish Date']).dt.strftime('%Y-%m-%d')
combine['Year_Quarter'] = pd.to_datetime(combine['Publish Date']).dt.to_period('Q').astype(str)

如何将此日期格式转换为:

Q12014
Q12015
Q22015
Q32016

谢谢你的帮助!

标签: pythonpandasdatedatetime

解决方案


你可以试试这个strftime来获得自定义格式:

combine['Year_Quarter'] = pd.to_datetime(combine['Publish Date']).dt.to_period("Q").dt.strftime('Q%q%Y')

或者正如@Barmar 和@anky 在评论中所建议的那样,您也可以对该列进行切片:

combine['Year_Quarter'] = pd.to_datetime(combine['Publish Date']).dt.to_period('Q').astype(str) 
combine['Year_Quarter']=combine['Year_Quarter'].str[-2:].add(combine['Year_Quarter'].str[:4])

两个输出:

combine['Year_Quarter']

Q12014
Q12015
Q22015
Q32016

推荐阅读