用每个季度的“限制”定义一个字典。我会做这样的事情:
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()
这个例子打印出来:
'2020-Q2'