Ansible:比较过去一小时两个日期之间的差异 [英] Ansible: compare difference between two dates for the last hour

查看:31
本文介绍了Ansible:比较过去一小时两个日期之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一种方法可以使用 ansible_date_time 来比较 当前时间有另一个日期(aws ec2 启动时间)所以我将能够知道它是否发生在过去一小时?

there is a way to compare between the current time using ansible_date_time with another date (aws ec2 launch time) So I will be able to know if it happened in the last hour?

我有以下变量 ec2_launch_time: 2018-01-04T15:57:52+00:00

我知道我可以用以下方法比较(来自此处此处):

I know that I can compare days with the following method (from here and here):

"{{ (ansible_date_time.iso8601[:19] | to_datetime('%Y-%m-%dT%H:%M:%S') - ec2_launch_time[:19] | to_datetime('%Y-%m-%dT%H:%M:%S')).days }}"

如果我得到 0 我会知道它发生在同一天,但如果日期之间的差异是 1 小时,我正在寻找一种方法来判断真假(同一天).

if I will get 0 I will know that it happened on the same day but I'm looking for a way to get true or false if the difference between the dates are 1 hour (on the same day).

有一个过滤器可以用于这种或优雅的方式来编写它或仅使用外壳(例如 this)?

there is a filter for this or elegant way to write this or only using shell (like this)?

推荐答案

通过减去两个日期,你得到一个 timedelta Python 对象.

By subtracting two dates, you get a timedelta Python object.

您可以使用 total_seconds 方法 以秒为单位获得确切的差异.添加一些基本算术以获得完整的小时数:

You can use total_seconds method to get the exact difference in seconds. Add some basic arithmetic to get the number of full hours:

---
- hosts: localhost
  gather_facts: no
  connection: local
  vars:
    date_later: 2018-01-05 08:30:00
    date_earlier: 2018-01-05 06:50:00
  tasks:
    - debug:
        msg: "{{ ( (date_later - date_earlier).total_seconds() / 3600 ) | int }}"

返回:

ok: [localhost] => {
    "msg": "1"
}

在你想要的条件中使用上面的表达式.

Use the above expression in the condition you want.

这篇关于Ansible:比较过去一小时两个日期之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆