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

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

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

suffix = '_22_q1'
previous_suffix = '_21_q2'

>Solution :

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_'
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