Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert quarters to long date using Python

I have a dataset where I would like to convert the values within a specific column to a long date.
The long date will always be the first of the first month of that quarter.

**Ex. Q122 = 1/1/2022,   Q222 = 4/1/2022,  Q322 = 7/1/2022,  Q422 = 10/1/2022**

Data

ID   Date   Location

AA   Q123   NY
BB   Q425   CA
CC   Q226   NY
CC   Q326   NY

Desired

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

ID   Date   Location   LongDate

AA   Q123   NY         1/1/2023
BB   Q425   CA         10/1/2025
CC   Q226   NY         4/1/2026
CC   Q326   NY         7/1/2026

Doing

df['Date'] = pd.PeriodIndex(qs, freq='Q').to_timestamp()

Error is unable to parse. I am thinking there has to be initial conversion here. Researching this, any suggestion is appreciated.

>Solution :

You can do with reversing the pattern:

pd.to_datetime(df['Date'].str[-2:]+df['Date'].str[:2]).dt.strftime('%m/%d/%Y')

0    01/01/2023
1    10/01/2025
2    04/01/2026
3    07/01/2026
Name: Date, dtype: object

Note that .dt.strftime('%m/%d/%Y') should be only used if you want them as strings. I recommend you dont use them and let it be date

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading