對不起,我不是 python 專家。我想自動創建以下串列,第一季度需要始終是下一個。因此,如果我今天(23/02/22)這樣做,第一個將是 Q022022,如果我在 23/05/22 日期這樣做,第一個將是 Q032022。
先感謝您
uj5u.com熱心網友回復:
得到四分之一
current_quarter = ((month-1) // 3) 1
next_quarter = current_quarter 1
如果是上一季度(4)則需要用modulo(%)得到第一季度(1),需要增加year
next_quarter = ((next_quarter-1) % 4) 1
if next_quarter < current_quarter:
year = year 1
你可以month直接year從字串`
date = "23/02/22"
month = int(date[3:5])
year = int(date[7:9]) 2000
或者你可以datetime用來決議它
date = "23/02/22"
dt = datetime.datetime.strptime(date, '%d/%m/%y')
month = dt.month
year = dt.year
最小的作業示例
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('---')
結果:
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
---
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/432267.html
