Convert seconds in past to timestamp (e.g. uptime or since last event), incl. slight error

Hey there,
thought I could share this.

The following sensor template solves two tasks:

  • Derive a timestamp from a given number of seconds (assuming they point in the past)
  • Ignore small changes from update to update (so the sensor in Home Assistant doesn’t see a state change regularly)

(In my example a microcontroller publishes its uptime via MQTT - however as it doesn’t know the absolute time, it will publish its uptime in seconds since startup.)

# "sensor.uptime" holds the number of seconds
template:
  - sensor:
      - name: uptime_since
        unique_id: uniqueid__uptime_since
        state: >
          {% if is_state("sensor.uptime", "unavailable") %}
            "unavailable"
          {% else %}
            {% set new_timestamp_s = as_timestamp(now() - timedelta(seconds=(states('sensor.uptime') | int()))) | round(0) %}
            {% if is_state("sensor.uptime_since", "unknown") or is_state("sensor.uptime_since", "unavailable") %}
              {{ new_timestamp_s | timestamp_local() }}
            {% else %}
              {% set current_timestamp_s = as_timestamp(states('sensor.uptime_since')) | round(0) %}
              {% set difference_s = (current_timestamp_s - new_timestamp_s) | abs %}
              {% if difference_s > 60 %}
                {{ new_timestamp_s | timestamp_local() }}
              {% else %}
                {{ states('sensor.uptime_since') }}
              {% endif %}
            {% endif %}
          {% endif %}
        device_class: timestamp
        icon: mdi:calendar-clock

Hope this is helpful. Feel free to ask questions or suggest improvements! I’m sure this can be reduced in length?

Cheers