I am trying to convert a date to Year-Quarter format. Below is my code
import pandas as pd
import datetime as datetime
pd.PeriodIndex(datetime.date(2020, 6, 15), freq='Q-MAR').strftime('Q%q')
Which this I am getting below error:
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
Can you please help how to correct this error? I expect to get result as 2020-Q2.
CodePudding user response:
If working with scalar need 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
Or add [] for one element list:
print (pd.PeriodIndex([datetime.date(2020, 6, 15)], freq='Q-MAR').strftime('Q%q'))
Index(['Q1'], dtype='object')
