Skip to content

Instantly share code, notes, and snippets.

@ycku
Created March 21, 2025 12:58
Show Gist options
  • Save ycku/6a908ea50b8e3c749311ced4be9cbeeb to your computer and use it in GitHub Desktop.
Save ycku/6a908ea50b8e3c749311ced4be9cbeeb to your computer and use it in GitHub Desktop.
Fetch daily costs on AWS
# pip install boto3
import boto3
from datetime import datetime, timedelta
# 初始化 Cost Explorer 客戶端
client = boto3.client('ce')
# 設定日期範圍
end_date = datetime.now().strftime('%Y-%m-%d')
start_date = (datetime.now() - timedelta(days=30)).strftime('%Y-%m-%d')
# 呼叫 GetCostAndUsage API
response = client.get_cost_and_usage(
TimePeriod={
'Start': start_date,
'End': end_date
},
Granularity='DAILY',
Metrics=['UnblendedCost']
)
# 輸出結果
for result in response['ResultsByTime']:
print(f"Date: {result['TimePeriod']['Start']}, Cost: {result['Total']['UnblendedCost']['Amount']} {result['Total']['UnblendedCost']['Unit']}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment