You have a list of datetime objects. Your task is to extract the month and quarter values from each of your list elements into several new lists: one consisting of month numbers, one of month names and the last of quarters.
Extract month and quarter from Python dates
First we will create a list of datetime objects. I like to use the pandas library and specifically the pd.date_range() method for that:
import pandas
import datetime
dates = pd.date_range(start=my_dt, periods = 6, freq = 'B' ).to_pydatetime().tolist()
print (dates)
This will return the following list:
[datetime.datetime(2023, 3, 29, 0, 0), datetime.datetime(2023, 3, 30, 0, 0), datetime.datetime(2023, 3, 31, 0, 0), datetime.datetime(2023, 4, 3, 0, 0), datetime.datetime(2023, 4, 4, 0, 0), datetime.datetime(2023, 4, 5, 0, 0)]
Next we will use simple list comprehensions to build our lists.
Get month number from dates
my_month_lst = [d.month for d in dates]
print(my_month_lst)
This will return:
[3, 3, 3, 4, 4, 4]
Extract month names
For this example we will use the strftime formatter, that allows to convert datetime to string values, in this case we” use the %B to write the month full name.
my_month_name_lst = [d.strftime('%B') for d in dates]
print(my_month_name_lst)
This returns:
['March', 'March', 'March', 'April', 'April', 'April']
Get quarter names from dates
We’ll first define a simple function which we’ll use to convert the dates to a quarter:
def month_to_quarter (month):
if month in [1,2,3]:
return 'Q1'
elif month in [4,5,6]:
return 'Q2'
elif month in [7,8,9]:
return 'Q3'
else: return 'Q4'
Then we’ll call the function:
my_qtr_lst = [month_to_quarter (d.month) for d in dates]
This will render the following quarter list:
['Q1', 'Q1', 'Q1', 'Q2', 'Q2', 'Q2']
Follow up learning
How to cast a list of strings to Datetime objects in Python3 scripts?