Difference in seconds between input_datetime and now()

in my template I want to compare my input_datetime with now() and I want:
TRUE → if input_datetime - now() < 60 seconds.

This not works

{{ now() - (states.input_datetime.volume_night_alexas.state)}}

Could you help me?

1 Like
  • now() reports the current date and time as a datetime object.
  • Your input_datetime entity reports time as a string.

You can’t subtract a string from a datetime object.

You have to ensure both are datetime objects or integers representing their respective Unix timestamps.

Try this version which converts the input_datetime’s value to a datetime object.

{{ now() - now().replace(hour=state_attr('input_datetime.volume_night_alexas', 'hour'), minute=state_attr('input_datetime.volume_night_alexas', 'minute')) < timedelta(seconds=60) }}
1 Like

I convert to timestamps so I can deal with the math in integers and not mess with timedelta objects and all the additional backend math required to process it

{%- set ts_event = as_timestamp(states.[[entity]].state) %}
{%- set ts_now = as_timestamp(now())|round(0) %}
{%- set ts_delta = (ts_now - ts_event) %}

I usually use this to deal with events in the past, so past times get positive deltas, and future times are negative, they can be reversed

In the example you posted, the first line will produce None because, in this case, the input_datetime’s value is merely a time string (see screenshot in first post: 23:00:00). That will cause the third line to fail.

unsupported operand type(s) for -: ‘int’ and ‘NoneType’

Correct, I am using datetime with a full date, which is needed to get a true UNIX timestamp

In this case, if Now is 24 hours and 10s away from the datetime… will it report only 10s?

My mistake; I assumed you were providing Reinqusito a functional solution.