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

140
March 26, 2022, at 09:10 AM

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'
Answer 1

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_'
Rent Charter Buses Company
READ ALSO
Custom train-test split using two stratified classes

Custom train-test split using two stratified classes

I am trying to use NLP techniques to predict the mental status of patients at the time doctor's notes were takenI have two classes, suffix (multilabel) as well as mental_status (binary, Lucid or Delirium)

175
I'm learning Python and want to remove data from a CSV file

I'm learning Python and want to remove data from a CSV file

The CSV file I'm trying to change has 2 columns

137