调用Azure Cost Management API查询上月费用遇TheLastMonth不支持问题求助
解决Azure Cost Management API使用TheLastMonth报错的问题
问题根源
Azure Cost Management API 2023-11-01版本并未支持TheLastMonth这个timeframe枚举值,官方定义的有效timeframe选项包括:MonthToDate、BillingMonthToDate、TheLastWeek、TheLast7Days、TheLast30Days、PreviousBillingMonth、YearToDate、Custom等。
解决方案
1. 使用PreviousBillingMonth获取上月计费周期费用
如果你的需求是获取上一个计费周期的Azure使用费用,直接将timeframe设置为PreviousBillingMonth即可,这是官方提供的替代方案,无需自定义日期范围:
{ "type": "ActualCost", "timeframe": "PreviousBillingMonth", "dataset": { "granularity": "Daily", "aggregation": { "totalCost": { "name": "PreTaxCost", "function": "Sum" } } } }
2. 严格按自然月获取数据(动态生成日期)
如果必须获取自然月的上月数据,且不想手动维护日期,可以通过代码动态计算上月的起始和结束日期,再结合Custom timeframe实现:
{ "type": "ActualCost", "timeframe": "Custom", "timePeriod": { "start": "YYYY-MM-01", // 代码动态生成上月第一天 "end": "YYYY-MM-DD" // 代码动态生成上月最后一天 }, "dataset": { "granularity": "Daily", "aggregation": { "totalCost": { "name": "PreTaxCost", "function": "Sum" } } } }
示例Python代码生成日期:
from datetime import datetime, timedelta last_month = datetime.now().replace(day=1) - timedelta(days=1) start_date = last_month.replace(day=1).strftime("%Y-%m-%d") end_date = last_month.strftime("%Y-%m-%d")
验证说明
PreviousBillingMonth在API 2023-11-01版本中是有效枚举值,可直接替代TheLastMonth满足上月费用查询需求;若需自然月数据,动态生成日期的Custom方案是最便捷的替代方式。
内容的提问来源于stack exchange,提问作者gotothesky
相关产品推荐
相关产品推荐

