3

I haven't found anything for this yet.

I am using Ansible and I'm trying to change some values after a decent amount of time.

But my problem is I get a value like:

2020 Nov 19

But I need it to be like:

2020 11 19

How can I do this?

β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83
VallingSki
  • 133
  • 4

1 Answers1

5

using to_datetime and strftime you can achieve it. the filters to apply would be:

"{{ '%Y %m %d' | strftime(( my_date_string | to_datetime('%Y %b %d')).strftime('%s')) }}"

as reference, please see the examples here. The idea is to convert your string value to datetime using the to_datetime, then to epoch time using strftime, and finally reformat that to your desired YYYY MM DD.

A PB with 3 example dates:

---
- hosts: localhost
  gather_facts: false
  vars:
    my_date_examples: 
    - "2020 Nov 04"
    - "2020 Apr 11"
    - "2020 Aug 23"

  tasks:
  - name: reformat date string
    debug:
      msg: "{{ '%Y %m %d' | strftime(( item | to_datetime('%Y %b %d')).strftime('%s')) }}"
    loop: "{{ my_date_examples }}"

output:

TASK [reformat date string] *******************************************************************************************************************************************************************************************
ok: [localhost] => (item=2020 Nov 04) => {
    "msg": "2020 11 04"
}
ok: [localhost] => (item=2020 Apr 11) => {
    "msg": "2020 04 11"
}
ok: [localhost] => (item=2020 Aug 23) => {
    "msg": "2020 08 23"
}

cheers

ilias-sp
  • 6,135
  • 4
  • 28
  • 41