【问题标题】:How to convert a date to Quarter如何将日期转换为季度
【发布时间】:2022-01-10 05:58:54
【问题描述】:

我正在尝试将日期转换为 Year-Quarter 格式。下面是我的代码

import pandas as pd
import datetime as datetime

pd.PeriodIndex(datetime.date(2020, 6, 15), freq='Q-MAR').strftime('Q%q')

这是我得到以下错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.9/site-packages/pandas/core/indexes/period.py", line 241, in __new__
    data = period_array(data=data, freq=freq)
  File "/usr/local/lib/python3.9/site-packages/pandas/core/arrays/period.py", line 892, in period_array
    data = list(data)
TypeError: 'datetime.date' object is not iterable

您能帮忙解决这个错误吗?我希望得到2020-Q2的结果。

【问题讨论】:

    标签: python pandas datetime


    【解决方案1】:

    如果使用标量需要Period:

    print (pd.Period(datetime.date(2020, 6, 15), freq='Q-MAR').strftime('Q%q'))
    Q1
    
    
    print (pd.Period(datetime.date(2020, 6, 15), freq='Q-MAR').strftime('%Y-Q%q'))
    2020-Q1
    
    
    print (pd.Period(datetime.date(2020, 6, 15), freq='Q').strftime('%Y-Q%q'))
    2020-Q2
    

    或者为一个元素列表添加[]

    print (pd.PeriodIndex([datetime.date(2020, 6, 15)], freq='Q-MAR').strftime('Q%q'))
    Index(['Q1'], dtype='object')
    

    【讨论】:

      猜你喜欢
      • 2022-11-09
      • 2021-07-26
      • 2016-02-10
      • 2018-10-31
      • 1970-01-01
      • 2015-09-13
      • 1970-01-01
      • 1970-01-01
      • 2023-01-22
      相关资源
      最近更新 更多