Template sensor with a timestamp

I’m trying to use three attributes from an existing sensor to create a new template sensor that shows as “Clear” if the timestamp is >3 seconds from now(). The sensor (sensor.camera_g3_log) should show the attribute ‘eventlog’ as long as the timestamp from attributes ‘date’ and ‘time’ are less than 3 seconds from the present time. This allows the sensor to reset after an event in the log and allows me to issue multiple events with the same data.

Unfortunately my template doesn’t seem to be working, would love some help in debugging!

        camera_g3_eventlog_recent:
            friendly_name: 'Camera G3 Recent Event Log'
            value_template: >
              {% set event_date = state_attr('sensor.camera_g3_log', 'date') %}
              {% set event_time = state_attr('sensor.camera_g3_log', 'time') %}
              {% if event_date and event_time %}
                {% set event_datetime = as_datetime(event_date + ' ' + event_time) %}
                {% set now = utcnow() %}
                {% if now - event_datetime < timedelta(seconds=3) %}
                  {{ state_attr('sensor.camera_g3_log', 'eventlog') }}
                {% else %}
                  Clear
                {% endif %}
              {% else %}
                Clear
              {% endif %}

can u go to dev tools states and show us exactly what sensor.camera_g3_log attributes values are

I think you are comparing timezones aware datetime with unaware datetime. Assuming the attributes are local time try this

            value_template: >
              {% set event_date = state_attr('sensor.camera_g3_log', 'date') %}
              {% set event_time = state_attr('sensor.camera_g3_log', 'time') %}
              {% if event_date and event_time %}
                {% set event_datetime = strptime(event_date + ' ' + event_time, '%m/%d/%Y %I:%M:%S %p') %}
                {% if now() - event_datetime.astimezone() < timedelta(seconds=3) %}
                  {{ state_attr('sensor.camera_g3_log', 'eventlog') }}
                {% else %}
                  Clear
                {% endif %}
              {% else %}
                Clear
              {% endif %}

Unfortunately the sensor is now saying unavailable

sorry, made an update. grab it again?

That did the trick! Thank you so much!!

1 Like

great. glad it’s working for you!