Home > database >  Given the quarter name return the start and end dates
Given the quarter name return the start and end dates

Time:08-24

I have a string like "2015-Q1". What is the best way to return the start date and end date of the given quarter?

Input: 2015-Q1

Expected Output: (2015-01-01,2015-03-31)

CodePudding user response:

def func():
    quarter = {
        'Q1' : ['01-01', '03-31'],
        'Q2' : ['04-01', '06-30'],
        'Q3' : ['07-01', '09-30'],
        'Q4' : ['10-01', '12-31']
    }
    
    quarter_input = input()
    
    goal_first = quarter_input[:-2]   quarter[quarter_input[-2:]][0]
    goal_last = quarter_input[:-2]   quarter[quarter_input[-2:]][1]
    
    return (goal_first, goal_last)

CodePudding user response:

Create a dictionary keyed on Q1-4. For each key, assign the beginning and end dates for that quarter. Then:

Q = {'Q1': ('01-01', '03-31'), 'Q2': ('04-01', '06-30'), 'Q3': ('07-01', '09-30'), 'Q4': ('10-01', '12-31')}

def quarter(sd):
    yy, qq = sd.split('-')
    b, e = Q[qq]
    return f'({yy}-{b},{yy}-{e})'

print(quarter('2015-Q1'))

Output:

(2015-01-01,2015-03-31)

CodePudding user response:

You can create a dictionary with start and end dates with the month for each quarter and use the last 2 characters of the string as key

a={'Q1':['01-01','03-31']}
b='2015-Q1'
for i in a[b[-2:]]:
    print(b[:-2] i)

CodePudding user response:

def get_quarter_date(quarter):
    year,quarter=quarter.split("-")
    year=int(year)
    quarter_map={"Q1":1,"Q2":4,"Q3":7,"Q4":10}
    quarter=int(quarter_map[quarter])
    start=pd.to_datetime(str(year) "-" str(quarter) "-01")
    end=pd.to_datetime(str(year) "-" str(quarter 3) "-01")-pd.DateOffset(days=1)
    return start,end
  • Related