2
$\begingroup$

I have been trying to convert stuff like 2002Q3 to 2002-09-01, but if I use the following, it will convert 2002Q3 to 2002-07-01:

pd.PeriodIndex(['2002Q3], freq='Q').to_timestamp()

How can I get it to match to 2002-06-01, instead? For example, I want 2002Q1 to correspond to 2002-03-01, 2002Q2 to 2002-06-01, 2002Q3 to 2002-09-01, and 2002Q4 to 2002-12-01. Thanks!

$\endgroup$

1 Answer 1

4
$\begingroup$

Since your end goal is just datetime64, use replace with to_datetime.

  • Given a Series of YYYYQQ strings:

    qtr = pd.Series([f'{y}Q{q}' for y in range(2000, 2010) for q in (1, 2, 3, 4)])
    
    # 0     2000Q1
    # 1     2000Q2
    # 2     2000Q3
    # 3     2000Q4
    # 4     2001Q1
    # ...
    # 38    2009Q3
    # 39    2009Q4
    # dtype: object
    
  • replace the QQ portion with your desired -mm-dd and convert to_datetime:

    mapping = {
        'Q1': '-03-01',
        'Q2': '-06-01',
        'Q3': '-09-01',
        'Q4': '-12-01',
    }
    pd.to_datetime(qtr.replace(mapping, regex=True))
    
    # 0    2000-03-01
    # 1    2000-06-01
    # 2    2000-09-01
    # 3    2000-12-01
    # 4    2001-03-01
    # ...         ...
    # 38   2009-09-01
    # 39   2009-12-01
    # dtype: datetime64[ns]
    
$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.