Is there a Ansible function to convert date string to epoch?

11,399

Solution 1

Ansible has a to_datetime filter, documented here. That page includes the following examples:

# Get total amount of seconds between two dates. Default date format is %Y-%m-%d %H:%M:%S but you can pass your own format
{{ (("2016-08-14 20:00:12" | to_datetime) - ("2015-12-25" | to_datetime('%Y-%m-%d'))).total_seconds()  }}

# Get remaining seconds after delta has been calculated. NOTE: This does NOT convert years, days, hours, etc to seconds. For that, use total_seconds()
{{ (("2016-08-14 20:00:12" | to_datetime) - ("2016-08-14 18:00:00" | to_datetime)).seconds  }}
# This expression evaluates to "12" and not "132". Delta is 2 hours, 12 seconds

# get amount of days between two dates. This returns only number of days and discards remaining hours, minutes, and seconds
{{ (("2016-08-14 20:00:12" | to_datetime) - ("2015-12-25" | to_datetime('%Y-%m-%d'))).days  }}

Using this filter, you could convert a date to string to a unix epoch time like this:

- debug:
    msg: "{{ ('2019-05-06 15:50:00'|to_datetime).strftime('%s') }}"

Which would output:

TASK [debug] **********************************************************************************
ok: [localhost] => {
    "msg": "1557172200"
}

Solution 2

I had to convert a string for the user module. The other approaches her didn't work for me.

You can use strftime:

vars:

expire_date: 2020-07-12

task:

- name: "create user"
  user:
    name: user
    expires: "{{ expire_date.strftime('%s') }}"
  become: true
Share:
11,399
vshankara
Author by

vshankara

Updated on December 11, 2022

Comments

  • vshankara
    vshankara over 1 year

    I am looking to convert date input variable into epoch. I did not see a Ansible function to help me with this.

    For eg:

    Date is a variable of format: %m/%d/%Y %H:%M:%S, this needs to be converted to epoch secs.