Bootstrap FreeKB - Ansible - Make a date human readable using the strftime filter
Ansible - Make a date human readable using the strftime filter

Updated:   |  Ansible articles

There are a few different ways to do something with datetime in Ansible.

The strftime filter is used to convert a date object into a string.

In this example, %Y-%m-%d is converted into a string.

---
- hosts: all
  tasks:
  - name: convert '%Y-%m-%d' into a string
    debug:
      msg: "{{ '%Y-%m-%d' | strftime }}"
...

 

Something like this should be returned.

TASK [convert '%Y-%m-%d' into a string]
ok: [server1.example.com] => {
    "msg": [
        "2024-08-12"
    ]
}

 

In this example, %Y-%m-%d %H:%M:%S is converted into a string.

---
- hosts: all
  tasks:
  - name: convert '%Y-%m-%d %H:%M:%S' into a string
    debug:
      msg: "{{ '%Y-%m-%d %H:%M:%S' | strftime }}"
...

 

Something like this should be returned.

TASK [convert '%Y-%m-%d %H:%M:%S' into a string]
ok: [server1.example.com] => {
    "msg": [
        "2024-08-12 03:50:12"
    ]
}

 

You can also pass in certain parameters to strftime. In this example, ansible_date_time.epoch is used to get the current epoch timestamp and to then create a fact named plus_24_hours and then strftime is used to return the datetime as a string.

---
- hosts: all
  tasks:
  - name: set_fact plus_24_hours
    ansible.builtin.set_fact:
      plus_24_hours: "{{ ansible_date_time.epoch|int + 86400 }}"

  - ansible.builtin.debug:
      var: next_sunday_epoch

  - ansible.builtin.debug:
      msg: "{{ '%Y-%m-%d %H:%M:%S' | strftime(plus_24_hours) }}"
...

 

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter d73edf in the box below so that we can be sure you are a human.