Ansible - Convert timestamp to some human readable format

Viewed 29

I have a variable with a timestamp which I need to convert to a human readable format. Here is an example:

- name: Extract timestamp from output
  set_fact:
    timestamp: "{{ output.json | json_query(snap_timestamp) }}"
  vars:
    snap_timestamp: "[*].{Timestamp: timestamp}"

Output I get is:

{
    "msg": "timestamp is [{'Timestamp': 1662628573}]"
}

I then tried to convert it with these filters but it doesn't work

 - name: Convert timestamp to a human readable format
   set_fact:
      snap_timestamp_converted: "{{ snap_timestamp[0] | to_json | '%Y-%m-%d %H:%M:%S' | strftime }}"

Any idea?

Thanks.

1 Answers

The correct syntax is below. See Handling dates and times

snap_timestamp_converted: "{{ '%Y-%m-%d %H:%M:%S'|strftime(timestamp) }}"

For example, the playbook

- hosts: localhost
  vars:
    timestamp: 1662628573
    snap_timestamp_converted: "{{ '%Y-%m-%d %H:%M:%S'|strftime(timestamp) }}"
  tasks:
    - debug:
        var: snap_timestamp_converted

gives

  snap_timestamp_converted: '2022-09-08 11:16:13'
Related