Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible: compare difference between two dates for the last hour

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?

I have the following var 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 }}"

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).

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

like image 453
dsaydon Avatar asked Jan 04 '18 19:01

dsaydon


1 Answers

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

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

returns:

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

Use the above expression in the condition you want.

like image 197
techraf Avatar answered Nov 10 '22 14:11

techraf