Home > Enterprise >  needed to extract the quarter from a given date
needed to extract the quarter from a given date

Time:11-24

Problem 1 As an analyst, you had to present the quarterly performance results of your client. The data which you were provided was on daily basis. To complete this task, you needed to extract the quarter from a given date. For example: if the date lies between 1st Jan, 2020 - 31st March, 2020, you need to extract the corresponding quarter as '2020-Q1'

if the date lies between 1st April, 2020 - 30th June, 2020, the extracted quarter will be '2020-Q2'

if the date lies between 1st July, 2020 - 30th September, 2020, the extracted quarter will be '2020-Q3'

if the date lies between 1st October, 2020 - 31st Decemeber, 2020 then the extracted quarter will be '2020-Q4'

CodePudding user response:

Hi and welcome to stackoverflow. I'm sure that this answer to a similar question will certainly help you.

Here is a quick summary of the above answer. Basically, you just need to check what month a given date is from and convert it to a number (1 to 12). If you subtract 1 from this (so it runs from 0 for january to 11 for december) and devide this number by 3 using integer division you get the quarter information you are looking for in the format 0 to 3. If you just add 1 again you get the correct quarter you are looking for.

Or using python code taken from the answer I linked above:

def printQuarter(month):
    print((month-1)//3   1)

printQuarter(1)  # january, result: 1
printQuarter(4)  # april, result: 2
printQuarter(12) # december, result: 4

Alternatively, you could of course use if-else statements to solve this problem, as you suggested with the if-statement tag in your question. This certainly works but is far less elegant. If for some reason you still want to do this, you could do e.g.:

if month <= 3:
    print("Q1")
elif month <= 6:
    print("Q2")
elif month <= 9:
    print("Q3")
else:
    print("Q4")

CodePudding user response:

Define a dictionary with the 'limits' of each quarter. I would do something like this:

from datetime import date

quarters = {
            '2020-Q1': ((2020, 1, 1), (2020, 3, 31)),
            '2020-Q2': ((2020, 4, 1), (2020, 6, 30)),
            '2020-Q3': ((2020, 7, 1), (2020, 9, 30)),
            '2020-Q4': ((2020, 10, 1), (2020, 12, 31))
            }

def get_quarter(my_date):
    try:
        if not isinstance(my_date, date): #Check if the input is a date
            raise TypeError
        for quarter, limits in quarters.items():
            if date(*limits[0]) <= my_date <= date(*limits[1]): 
                return quarter 
    except TypeError:
        ... # Handle exception

def main():

    my_date = date(2020, 4, 15) #Define a valid input
    print(get_quarter(my_date)) #Run the function

if __name__ == '__main__':
    main()
  • Related