i trying choose day in january , july of every year spanning period between 2 datetime objects (row['orig_iss_dt'] , row['maturity_dt']) , insert them my_dict. since, row['maturity_dt'] in dataframe df multiple of 6 months today (july), thought code below this. however, isn't working expected date's in months of april, may , june. i've tested monthdelta function , works expected.
# number of months between 2 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 pick out jan , july between 2 datetimes , insert them dict (i,row) in df.iterrows(): my_dict = {} date = datetime.datetime.strptime(row['maturity_dt'], '%y-%m-%d %h:%m:%s.%f') #setting date maturity date count = 0 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 maturity date till reaches orig_iss_dt print(date) count = count + 1 my_dict[count] = date thank you
some thoughts solution:
1) "date -= datetime.timedelta(6*30)"
we use line date year = 2015, month = 1, day = 30
dt = datetime.datetime(year=2015,month=1,day = 30) 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 not july.
2) recommend library "monthdelta" http://pythonhosted.org/monthdelta/ fix problem 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 maturity date till reaches orig_iss_dt print(date) count = count + 1 my_dict[count] = date 3) in case:
count = count + 1 my_dict[count] = date with code never write in my_dict[0]
Comments
Post a Comment