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

Ansible中JSON查询转换时间戳为日期时间失败求助

解决Ansible 2.9中字典列表时间戳转可读日期的JMESPath错误

错误原因

你遇到的JMESPathError: Unknown function: strftime()错误,核心原因是JMESPath不支持Ansible的strftime过滤器。json_query过滤器基于JMESPath实现,只能使用JMESPath内置函数,无法直接调用Ansible专属的过滤器方法。

解决方案

针对Ansible 2.9版本,推荐两种可靠的实现方式:

方法一:通过loop遍历转换并合并列表

这种方式逻辑直观,兼容性强,适合处理字典列表的批量字段修改:

- name: Update list of dicts
  hosts: localhost
  gather_facts: false
  vars:
    var1: 
      - { "name": "abc", "id": "23213123", "epochTime": 1687505936 }
      - { "name": "def", "id": "9c5219430000005c", "epochTime": 1687505950 }
    list_dict_human_readable: []

  tasks:
    - name: Convert epoch time to human-readable datetime
      set_fact:
        list_dict_human_readable: "{{ list_dict_human_readable + [ item | combine({ 'epochTime': item.epochTime | int | strftime('%Y-%m-%d %H:%M:%S') }) ] }}"
      loop: "{{ var1 }}"

    - debug:
        msg: "{{ list_dict_human_readable }}"

逻辑说明:

  • 用loop遍历原字典列表的每一项
  • 通过combine过滤器替换当前字典的epochTime字段值,将时间戳转为指定格式的可读字符串
  • 把处理后的字典追加到结果列表中

方法二:用map+combine实现批量转换(更简洁)

如果追求代码简洁性,可以使用map过滤器结合combine:

- name: Update list of dicts
  hosts: localhost
  gather_facts: false
  vars:
    var1: 
      - { "name": "abc", "id": "23213123", "epochTime": 1687505936 }
      - { "name": "def", "id": "9c5219430000005c", "epochTime": 1687505950 }

  tasks:
    - name: Convert epoch time to human-readable datetime
      set_fact:
        list_dict_human_readable: "{{ var1 | map('combine', {'epochTime': item.epochTime | int | strftime('%Y-%m-%d %H:%M:%S')}) | list }}"
      vars:
        item: "{{ item }}"
      loop: "{{ var1 }}"

    - debug:
        msg: "{{ list_dict_human_readable }}"

运行结果

执行上述任一方案后,都会得到预期的输出:

list_dict_human_readable: [ { "name": "abc", "id": "23213123", "epochTime": "2023-06-23 07:38:56"}, { "name": "def", "id": "9c5219430000005c", "epochTime": "2023-06-23 07:39:10"} ]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 08:57:46