我试图选择每年1月和7月的任何一天,跨越两个日期时间对象(row['orig_iss_dt']
和row['maturity_dt']
)之间的时段,并将其插入my_dict
。由于我的数据框row['maturity_dt']
中的df
是今天(7月)后6个月的倍数,我认为下面的代码会执行此操作。但是,由于我在4月,5月和6月的某些date
获得了monthdelta
,所以它没有按预期工作。我已经测试了# 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
函数,它按预期工作。
@XmlRootElement(name="clinical_study")
@XmlAccessorType(XmlAccessType.FIELD)
public class ClinicalStudy {
@XmlElement(name="primary_outcome")
private Outcome primaryOutcome;
@XmlElement(name="secondary_outcome")
private Outcome secondaryOutcome;
// getters and setters omitted for brevity
}
谢谢
答案 0 :(得分:0)
关于您的解决方案的一些想法:
1)“date - = datetime.timedelta(6 * 30)”
我们使用此行与日期年份= 2015年,月份= 1,日期= 30
dt = datetime.datetime(year=2015,month=1,day = 30)
for i in range(5):
dt -= datetime.timedelta(6*30)
print dt
我们得到:
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
不是七月。
2)我推荐你的图书馆“MonthDelta”http://pythonhosted.org/MonthDelta/ 这可以解决你的问题:
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)以防万一:
count = count + 1
my_dict[count] = date
使用此代码,您永远不会在my_dict [0]
中写入