Home > Back-end >  how I can create a list of quarter year (Q022022) automatically starting from the next quarter in py
how I can create a list of quarter year (Q022022) automatically starting from the next quarter in py

Time:02-24

I am sorry but I am not an expert of python. I would like to create the following list in automatic and the first quarter need to be always the next one. So if I do it today (23/02/22) the first one will be Q022022 if I do it in date 23/05/22 the first one need to be Q032022.

Thank you in advance

CodePudding user response:

To get quarter

current_quarter = ((month-1) // 3)   1
next_quarter = current_quarter   1

If it was last quarter (4) then it needs to use modulo (%) to get first quarter (1), and it needs to increase year

next_quarter = ((next_quarter-1) % 4)   1

if next_quarter < current_quarter:
   year = year   1

You could get month and year directly from string `

    date = "23/02/22"

    month = int(date[3:5])
    year  = int(date[7:9])   2000

or you can use datetime to parse it

    date = "23/02/22"

    dt = datetime.datetime.strptime(date, '%d/%m/%y')

    month = dt.month
    year  = dt.year

Minimal working example

import datetime

test = [
    ('23/01/22', 'Q022022'),
    ('23/02/22', 'Q022022'),
    ('23/03/22', 'Q022022'),
    
    ('23/04/22', 'Q032022'),
    ('23/05/22', 'Q032022'),
    ('23/09/22', 'Q042022'),
    ('23/12/22', 'Q012023'),
]

for date, expect in test:
    print('date:', date, '| expect:', expect)
    
    dt = datetime.datetime.strptime(date, '%d/%m/%y')
    m = dt.month
    y = dt.year

    #m = int(date[3:5])
    #y = int(date[7:9])   2000
    
    #print(dt, m, y)

    current_q = ((m-1) // 3)   1    # use months 0..11
    next_q = current_q   1
    next_q = ((next_q-1) % 4)   1   # use quarters 0..3
    #next_q = (current_q % 4)   1
    
    print('current:', current_q, '| next:', next_q)
    
    if next_q < current_q:
        y  = 1
        
    result = f'Q{next_q:02}{y}'
    
    print('result:', result, '| expect:', expect, '| comparition:', result == expect)
    print('---')

Result:

date: 23/01/22 | expect: Q022022
current: 1 | next: 2
result: Q022022 | expect: Q022022 | comparition: True
---
date: 23/02/22 | expect: Q022022
current: 1 | next: 2
result: Q022022 | expect: Q022022 | comparition: True
---
date: 23/03/22 | expect: Q022022
current: 1 | next: 2
result: Q022022 | expect: Q022022 | comparition: True
---
date: 23/04/22 | expect: Q032022
current: 2 | next: 3
result: Q032022 | expect: Q032022 | comparition: True
---
date: 23/05/22 | expect: Q032022
current: 2 | next: 3
result: Q032022 | expect: Q032022 | comparition: True
---
date: 23/09/22 | expect: Q042022
current: 3 | next: 4
result: Q042022 | expect: Q042022 | comparition: True
---
date: 23/12/22 | expect: Q012023
current: 4 | next: 1
result: Q012023 | expect: Q012023 | comparition: True
---
  • Related