6

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

techraf
  • 64,883
  • 27
  • 193
  • 198
dsaydon
  • 4,421
  • 6
  • 48
  • 52

1 Answers1

9

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.

techraf
  • 64,883
  • 27
  • 193
  • 198
  • 3
    thanks @techraf, this worked for me `(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')).total_seconds() / 3600 | int <= 1 ` – dsaydon Jan 09 '18 at 14:14