Reputation: 4807
I have a list 'A' the contents of which is datetime.datetime.
I want to obtain another list or array 'B' which stores the first day of month for each of the datetime in the list A.
I want to obtain another list or array 'C' which stores just the month number for each datetime in A.
Is it possible to achieve this in a smarter way other than using a for loop. I have grandfathered the code but I am at liberty to change the A, B, C into list or arrays, etc as it suits me.
date_format = "%m/%d/%Y"
st_dt = datetime.strptime( '02/01/2016', date_format )
en_dt = datetime.strptime( '03/31/2016', date_format )
A = [ st_dt + timedelta( days = x ) for x in range( ( en_dt - st_dt ).days + 1 ) ]
Edit: First day means First date e.g. if the date is 2/15/2016 then first date for my case would be 2/1/2016
Upvotes: 0
Views: 351
Reputation: 213125
Using pandas:
dts = [datetime(2016,2,1), datetime(2016,3,31)]
import pandas as pd
a = pd.DatetimeIndex(dts)
# a: <class 'pandas.tseries.index.DatetimeIndex'>
# [2016-02-01, 2016-03-31]
# Length: 2, Freq: None, Timezone: None
# b stores the first day of month for each of the datetime in the list a.
b = a.map(lambda x: x.replace(day=1))
# b: array([Timestamp('2016-02-01 00:00:00'),
# Timestamp('2016-03-01 00:00:00')], dtype=object)
# c stores just the month number for each datetime in a.
c = a.month
# c: array([2, 3], dtype=int32)
Upvotes: 1