Selecting specific months between two datetime objects

I am trying to select any day in January and July of each year spanning the period between two datetime objects ( row['orig_iss_dt']

and row['maturity_dt']

) and inserting them into my_dict

. Since row['maturity_dt']

my dataframe is df

multiple multiples of 6 months from today (July), I thought my code below would do it. However, it doesn't work as expected as I am getting a few date

in April, May and June. I tested the function monthdelta

and it works as expected.

# Number of months between two datetime objects
def monthdelta(d1, d2):
    delta = 0
    while True:
        mdays = monthrange(d1.year, d1.month)[1]
        d1 += timedelta(days=mdays)
        if d1 <= d2:
            delta += 1
        else:
            break
    return delta

#Trying to pick out Jan and July between the two datetimes and insert them into the dict
for (i,row) in df.iterrows():
    my_dict = {}
    date = datetime.datetime.strptime(row['maturity_dt'], '%Y-%m-%d %H:%M:%S.%f') #Setting date to be the maturity date
    count = 0
    for k in range(monthdelta(datetime.datetime.strptime(row['orig_iss_dt'], '%Y-%m-%d %H:%M:%S.%f'), datetime.datetime.strptime(row['maturity_dt'], '%Y-%m-%d %H:%M:%S.%f')), 0, -6):
        #list_of_coupons.append(row.coupon) 
        date -= datetime.timedelta(6*30) #Reducing from the maturity date till it reaches orig_iss_dt
        print(date)
        count = count + 1
        my_dict[count] = date

      

thank

+3


source to share


1 answer


Some thoughts on your solution:

1) "date - = datetime.timedelta (6 * 30)"

We use this string with date of year = 2015, month = 1, day = 30

dt = datetime.datetime(year=2015,month=1,day = 30)
     for i in range(5):
           dt -= datetime.timedelta(6*30)
           print dt

      

We get:

2014-08-03 00:00:00
2014-02-04 00:00:00
2013-08-08 00:00:00
2013-02-09 00:00:00
2012-08-13 00:00:00

      



It's not July.

2) I recommend you the "MonthDelta" library http://pythonhosted.org/MonthDelta/ which can solve your problem like this:

for k in range(monthdelta(datetime.datetime.strptime(row['orig_iss_dt'], '%Y-%m-%d %H:%M:%S.%f'), datetime.datetime.strptime(row['maturity_dt'], '%Y-%m-%d %H:%M:%S.%f')), 0, -6):
        #list_of_coupons.append(row.coupon) 
        date -= monthdelta.monthdelta(-6) #Reducing from the maturity date till it reaches orig_iss_dt
        print(date)
        count = count + 1
        my_dict[count] = date

      

3) just in case:

count = count + 1
my_dict[count] = date

      

with this code you will never write to my_dict [0]

0


source







All Articles