How could I convert a string of the format (YYYYQx) into a datetime object?

I have a table with a Date column and several other country-specific columns (see the picture below). I want to create a heatmap in Seaborn but for that I need the Date column to be a datetime object. How can I change the dates from the current format -i.e. 2021Q3 - to 2021-09-01 (YYYY-MM-DD)?

enter image description here

I have tried the solution below (which works for monthly data - to_date = lambda x: pd.to_datetime(x['Date'], format='%YM%m')), but it does not work for the quarterly data. I get a ValueError: 'q' is a bad directive in format '%YQ%q'... I could not find any solution to the error online...

# loop to transform the Date column's format
to_date = lambda x: pd.to_datetime(x['Date'], format='%YQ%q')                        
df_eurostat_reg_bank_x = df_eurostat_reg_bank.assign(Date=to_date) 

I have also tried this solution, but I get the first month of the quarter in return, whereas I want the last month of the quarter:

df_eurostat_reg_bank['Date'] = df_eurostat_reg_bank['Date'].str.replace(r'(\d+)(Q\d)', r'\1-\2')
df_eurostat_reg_bank['Date'] = pd.PeriodIndex(df_eurostat_reg_bank.Date, freq='Q').to_timestamp()
df_eurostat_reg_bank.Date = df_eurostat_reg_bank.Date.dt.strftime('%m/%d/%Y')
df_eurostat_reg_bank = df_eurostat_reg_bank.set_index('Date')

Thank you in advance!


I assume that your example of 2022Q3 is a string on the grounds that it's not a date format that I recognise.

Thus, simple arithmetic and f-strings will avoid the use of any external modules:

def convdate(d):
    return f'{d[:4]}-{int(d[5]) * 3 - 2:02d}-01'


for d in ['2022Q1','2022Q2','2022Q3','2022Q4']:
    print(convdate(d))

Output:

2022-01-01
2022-04-01
2022-07-01
2022-10-01

Note:

There is no attempt to ensure that the input string to convdate() is valid