0

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'

oguz ismail
  • 1
  • 16
  • 47
  • 69

4 Answers4

0

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")
0

I had an answer framed for you some time back! Alas! SO was down :-) . You can use an approach for finding the quarter using month of the date itself. See below.

from datetime import datetime

_date_str = "1 April, 2020"


def get_quarter_str(date_str):
    known_date = datetime.strptime(date_str, "%d %B, %Y")
    quarter = ((known_date.month - 1) // 3) + 1
    return f"{known_date.year} - Q{quarter}"


print(get_quarter_str(_date_str))
Kris
  • 8,680
  • 4
  • 39
  • 67
-1

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()

This example prints out:

'2020-Q2'
-1
date_year = '2020'
date_month = '07'

if (date_month >= "01") & (date_month <="03"):
      print("quarter = ", date_year + '-Q1')
elif (date_month >= "04") & (date_month <="06"):
      print("quarter = ", date_year + '-Q2')
elif (date_month >= "07") & (date_month <="09"):
      print("quarter = ", date_year + '-Q3')
else:
      print("quarter = ", date_year + '-Q4')
  • Thanks for trying to answer the question. However, this overlaps other answers, and it would be better to generalize it to take a `date`. Also, you should use `and` (logical and) instead of `&` (bitwise and) in logical expressions. – craigb Oct 30 '22 at 19:35