Template Help Comparing Dates

I have script on a device that updates its IP address into a sensor within HA. The script looks like this (truncated to make sense):

now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
ip_url = 'https://api64.ipify.org?format=json'
...
        response = urllib2.urlopen(ip_url,timeout=5)
        data = json.loads(response.read())
        updt_txt = data["ip"]
...
ha_payload = '{"state":"'+updt_txt+'","attributes":{"last_triggered":"'+now+'"}}'

The sensor then looks like this in HA:

I then have a sensor that evaluates the IP:

          {{ not ( is_state('sensor.ip', 'unknown') or is_state('sensor.ip', 'TIMEOUT') or is_state('sensor.ip', 'URL_ERROR') ) }}

I want to extend this sensor to also evaluate if the ip has not been updated within 10 minutes. I thought I could evaluate the attribute by using this:

as_timestamp(utcnow()) - as_timestamp(state_attr('sensor.ip','last_triggered'))

But that is giving me the UTC time conversion of the last_triggered item, which is already UTC converted. Is there a function that I should be using instead of as_timestamp? Thanks!

Change

to

now = datetime.now().isoformat()

and in your template add

(now() - state_attr('sensor.ip','last_triggered') | as_datetime).seconds > 10 * 60

Thanks for the incredibly fast help!

That pointed me in the right direction for sure. I had to change the python script to add the timezone because I was getting this error in my template: Can't subtract offset-naive and offset-aware datetimes. I have limited ability to add non-core python packages to that machine, so I just did it like this (I couldn’t get timezone imported or pytz). A bit hacky, but it seemed to work:

now = datetime.now().isoformat()
...
ha_payload = '{"state":"'+updt_txt+'","attributes":{"last_triggered":"'+now+'+00:00"}}'

And I set the template like this (less than, not greater than EDIT: because of the way my other logic was written):

{{ (now() - state_attr('sensor.ip','last_triggered') | as_datetime).seconds < 10*60}}

Now I just need to move it into the full sensor logic, but this gets me what I need!