user12625679
user12625679

Reputation: 696

Function to return current half quarter and previous two quarters based on current date

I would like to create a variable (suffix) that prints current year and quarter in this format: '_21_q2' and (previous_suffix) which is simply suffix - 2 quarters in this case: '_21_q2'

This is what I have tried so far:

currrent_date = datetime.datetime.now()
current_year = str(x.year)[2:]
current_quarter = str(((x.month-1)//3)+1)
suffix = ('_' + current_year + '_q' + currentquarter)
previous_suffix = ? 

Desired output

suffix = '_22_q1'
previous_suffix = '_21_q2'

Upvotes: 1

Views: 173

Answers (1)

fsl
fsl

Reputation: 3280

You should consider using strftime instead of calling str on a datetime object.

That said, here is one way leveraging pd.Period (since you have a pandas tag anyway):

import pandas as pd
from datetime import datetime

def format_quarter(date):
    year = date.strftime('%y')
    quarter = pd.Period(date, freq='q').strftime('%q')

    return f'_{year}_q{quarter}_'

# You're better off choosing a date first and formatting it afterwards
d1 = datetime.now()
d2 = d1 - pd.tseries.offsets.QuarterEnd(3)

suffix = format_quarter(d1)
previous_suffix = format_quarter(d2)

Output:

In [18]: suffix                                                                                        
Out[18]: '_22_q1_'

In [19]: previous_suffix                                                                               
Out[19]: '_21_q2_'

Upvotes: 1

Related Questions