【问题标题】:How to convert date format QQ-YYYY to a datetime object [duplicate]如何将日期格式QQ-YYYY转换为日期时间对象[重复]
【发布时间】:2019-06-02 05:17:10
【问题描述】:

我有一个 pandas 数据框,其中有一列应指示财务季度的结束。格式为“Q1-2009”类型。有没有一种快速的方法可以将这些字符串转换为时间戳为“2009-03-31”?

我只发现了“YYYY-QQ”格式的转换,反之则没有。

【问题讨论】:

  • pd.to_datetime 返回 ValueError: ('Unknown string format:', 'Q1-2009')。

标签: python pandas datetime


【解决方案1】:

使用replace 交换季度和年份部分创建季度期间,并使用PeriodIndex.to_timestamp 转换为日期时间:

df = pd.DataFrame({'per':['Q1-2009','Q3-2007']})

df['date'] = (pd.PeriodIndex(df['per'].str.replace(r'(Q\d)-(\d+)', r'\2-\1'), freq='Q')
                .to_timestamp(how='e'))

print (df)
       per       date
0  Q1-2009 2009-03-31
1  Q3-2007 2007-09-30

另一种解决方案是使用字符串索引:

df['date'] = (pd.PeriodIndex(df['per'].str[-4:] + df['per'].str[:2], freq='Q')
                .to_timestamp(how='e'))

【讨论】:

  • 完美运行!很有用。这种格式没有答案
【解决方案2】:

一种使用列表推导后跟pd.offsets.MonthEnd 的解决方案:

# data from @jezrael
df = pd.DataFrame({'per':['Q1-2009','Q3-2007']})

def get_values(x):
    ''' Returns string with quarter number multiplied by 3 '''
    return f'{int(x[0][1:])*3}-{x[1]}'

values = [get_values(x.split('-')) for x in df['per']]
df['LastDay'] = pd.to_datetime(values, format='%m-%Y') + pd.offsets.MonthEnd(1)

print(df)

       per    LastDay
0  Q1-2009 2009-03-31
1  Q3-2007 2007-09-30

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-01
    • 2017-01-17
    • 1970-01-01
    • 2013-10-27
    • 2017-03-08
    • 1970-01-01
    • 2011-01-17
    • 2015-04-21
    相关资源
    最近更新 更多