You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Power Query中插入变量实现API动态时间范围查询?

动态时间范围的Power Query API调用实现

这个需求完全可行,Power Query自带的日期时间函数可以轻松实现动态生成当前时间及往前24小时的时间范围,以下是修改后的代码和关键说明:

关键步骤说明

  • 用DateTime.LocalNow()获取当前系统时间,通过- #duration(1, 0, 0, 0)计算出24小时前的时间
  • 使用DateTime.ToText()将时间格式化为API要求的yyyy-MM-dd HH:mm:ss格式,再通过Uri.EscapeDataString()对时间字符串进行URL编码,避免特殊字符(比如冒号、空格)导致的请求错误
  • 将编码后的时间变量拼接进API请求URL中

修改后的完整代码

let
    // 定义动态时间变量:当前时间和24小时前的时间
    CurrentTime = DateTime.LocalNow(),
    FromTime = CurrentTime - #duration(1, 0, 0, 0), // 往前推24小时
    
    // 将时间格式化为API需要的字符串并做URL编码
    FormattedFromDate = Uri.EscapeDataString(DateTime.ToText(FromTime, "yyyy-MM-dd HH:mm:ss")),
    FormattedToDate = Uri.EscapeDataString(DateTime.ToText(CurrentTime, "yyyy-MM-dd HH:mm:ss")),
    
    // 拼接API请求URL,替换原固定日期为动态变量
    ApiUrl = "SOMEURL&fromDate=" & FormattedFromDate & "&toDate=" & FormattedToDate & "&fields=",
    
    // 发起API请求并处理响应
    Source = Json.Document(Web.Contents(ApiUrl,
        [Timeout=#duration(0, 0, 12, 0), 
        Headers=[Authorization="Bearer API TOKEN", 
        Accept="application/json"]])), 
    JsonResponse = Json.Document(Source),
    Data = JsonResponse, 
    Table = Table.FromRecords(Data)
in
    Table

额外提示

如果你的API对时间格式有更严格的要求(比如时区转换),可以用DateTimeZone.UtcNow()获取UTC时间,再转换为目标时区后格式化,确保时间范围的准确性。

内容的提问来源于stack exchange,提问作者owl_in

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 05:02:16