7

I am using jinja2 templates (with Ansible) and in it i require to check the difference between two dates. I do not have the epoch of the dates but i do have them in yyy-mm-dd HH:MM:ss format (no milliseconds). So my questions:

1) Is there a way in jinja2 to compare two dates ? I do not want to install any library, it has to be a built in feature.

2) If it cannot be done via jinja2, is there a quick logic i can implement to compare them ? Like converting to epoch ? (remember, no milliseconds)

ishan
  • 1,202
  • 5
  • 24
  • 44

2 Answers2

11

Building on @konstantin-suvorov's answer, you'll want to use the to_datetime filter.

{{ (date1|to_datetime - date2|to_datetime).days }}
Aidan Feldman
  • 5,205
  • 36
  • 46
3

Playbook:

- hosts: localhost
  tasks:
    - template: src=date.j2 dest=date.txt
      vars:
        date1: 2016-08-04 20:00:12
        date2: 2015-10-06 21:00:12

Template:

days {{ (date1 - date2).days }}

Output:

days 302
Konstantin Suvorov
  • 65,183
  • 9
  • 162
  • 193
  • for the task: - name: dates debug: msg="{{(ansible_winrm_certificate_expires - ansible_date_time.iso8601).days}}" I get: {"failed": true, "msg": "Unexpected templating type error occurred on ({{ansible_winrm_certificate_expires - ansible_date_time.date}}): unsupported operand type(s) for -: 'unicode' and 'unicode'"} – ishan Aug 04 '16 at 10:54
  • if your variables are strings, you are out of luck here... i guess a custom filter is your only way here. – Konstantin Suvorov Aug 04 '16 at 11:45