# 如何自动化的选择和优化EC2系列（五）如何整合RI续购日期

## 方案概述

1. 原有机型RI的成本，

（X-Y）* 原有机型RI每日成本

2.新机型RI的成本

（RI购买周期-X）*新机型RI每日成本

3.On-Demand 成本

（Y-X）*原有机型On-Demand每日价格

 ri_expired_date target_price source_price source_ondemand

ri_experied_date：源系统EC2 RI的到期日（日期类型）

target_price：目标EC2的一年标准RI实例价格

source _price：源EC2的一年标准RI实例价格

source _ondemand：源EC2的On-Demand实例价格（每小时）

``````import pandas as pd

from datetime import *

from datetime import date

from datetime import datetime

start_day = min(table['ri_expired_date']).date()

end_day = max(table['ri_expired_date']).date()

duration = (end_day - start_day).days

total_item = table.shape[0]

cost = []

for x in range(0, duration + 1):

sub_total = 0

for i in range(0, total_item):

current_item_date = (table.loc[[i]].ri_expired_date)[i].date()

# old price duration

op_day = ((current_item_date - start_day).days) - x

# on demand price duration

od_day = x - ((current_item_date - start_day).days)

# new price duration

np_day = (duration - x)

if op_day < 0:

op_day = 0

if od_day < 0:

od_day = 0

sub_total += ((table.loc[[i]].source_price)[i] / 365 * op_day + (table.loc[[i]].target_price)[i] / 365 * np_day + (table.loc[[i]].source_ondemand) * od_day * 24)[i]

cost.append(sub_total)

optimize_cost = min(cost)

print("{}   {}".format('    Date', '    Cost'))

for i in range(0, len(cost)):

if cost[i] == optimize_cost:

recommand_date = start_day + timedelta(days=i)

current_date = start_day + timedelta(days=i)

current_date = datetime.combine(current_date, datetime.min.time())

print("{}   {:.2f}".format(current_date.strftime('%Y-%m-%d'), cost[i]))

print ('\nRecommanded date to buy RI is {}'.format(recommand_date))``````

``````\$ python ri_plan.py
Date       Cost
2019-05-21   135170.43
2019-05-22   129999.90
2019-05-23   124917.96
2019-05-24   119982.30
2019-05-25   115046.64
2019-05-26   110110.98
2019-05-27   105175.32
2019-05-28   100239.65
2019-05-29   102823.48
2019-05-30   105407.30
2019-05-31   107991.12
2019-06-01   110574.95
2019-06-02   113158.77
2019-06-03   115742.59
2019-06-04   118326.42
2019-06-05   127722.57
2019-06-06   137703.24
2019-06-07   147683.91
2019-06-08   157664.58
2019-06-09   167645.26
2019-06-10   177625.93
2019-06-11   187606.60
2019-06-12   197587.27``````

#### ` Recommended date to buy RI is 2019-05-28`

https://github.com/shaneliuyx/awscnprice/tree/master/examples

————

## 本篇作者

### 刘育新

AWS ProServe 团队高级顾问，长期从事企业客户入云解决方案的制定和项目的实施工作。