是否有一个ansible函数将日期字符串转换为纪元

时间:2019-05-06 18:13:59

标签: ansible jinja2

我希望将日期输入变量转换为纪元。没看到一个辅助功能可以帮助我解决这个问题

例如: 日期是格式为%m /%d /%Y%H:%M:%S的变量,需要将其转换为纪元秒。

3 个答案:

答案 0 :(得分:4)

Ansible有一个to_datetime过滤器,记录在here中。该页面包含以下示例:

# 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  }}

使用此过滤器,您可以将日期转换为字符串,并将其转换为Unix纪元时间,如下所示:

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

哪个会输出:

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

答案 1 :(得分:0)

谢谢,那行得通。这是我在做什么

- name: update blackout file
  win_lineinfile:
    path: D:\temp\blackout\blackout.txt
    backup: yes
    insertafter: EOF
    line: "\\r\\nPermissions: admin=write\\r\\nadhoc:{{ regex_suppression }};{{ start_date_epoch }};{{ end_date_epoch }};{{ changerequest }}"
  vars:
    regex_suppression: "^(?i).*__({{serverlist | regex_replace(',','|')}}).*"
    start_date_epoch:  "{{ ( start_time | to_datetime).strftime('%s') }}"
    end_date_epoch:    "{{ ( end_time | to_datetime).strftime('%s') }}"

答案 2 :(得分:0)

我必须为用户模块转换一个字符串。她无法接受的其他方法。

您可以使用strftime

vars

expire_date: 2020-07-12

任务:

- name: "create user"
  user:
    name: user
    expires: "{{ expire_date.strftime('%s') }}"
  become: true