Timestamp from MQTT sensor?

This is driving me nuts. I can’t seem to figure out how to get my timestamp (which I believe is sent to me as a UNIX timestamp, I assume in UTC) into HA as a timestamp object.

If I make it a device-class of timestamp, it just says ‘unknown’. If I take that out, I get a number which online UNIX time converters seem to do properly.

Example state (from 2:09 PM Eastern/US on Dec 19, 2022): 1671477004429

Code:

mqtt:

  # Ecoflow MQTT Sensors

  sensor:

    # MQTT Topic Update metadata

    - name: "Ecoflow Params Last Updated"
      #icon: "mdi:clock"
      #device_class: timestamp
      force_update: true
      state_topic: "bridge-ecoflow//app/device/property/DAABZ5ZE8020852"
      value_template: >-
        {% set value = value_json['params']['latestTimeStamp'] %}
        {% if not value is defined %}
          {{ this.state }}
        {% else %}
          {{ value | int("invalid") }}
        {% endif %}

I see lots of threads people going from the ISO format to seconds to do math, but nobody going the other way?

So how do I get this into HA with a proper timestamp so I can compare stuff like whether it’s newer/older than other stuff like I’m accustomed to with other sensor attributes?

- name: "Ecoflow Params Last Updated"
  #icon: "mdi:clock"
  device_class: timestamp
  force_update: true
  state_topic: "bridge-ecoflow//app/device/property/DAABZ5ZE8020852"
  value_template: >-
    {% set ts = value_json.get('params', {}).get('latestTimeStamp')  %}
    {% if ts %}
      {{ (ts / 1000) | timestamp_local | as_datetime }}
    {% else %}
      {{ this.state }}
    {% endif %}

Thank you! I wouldn’t have guessed it would involve the function named “timestamp_local” for a GMT/UTC date/time conversion.

What’s the difference using the value_json.get().get() as opposed to what I’d done (that I’ve seen in guides)? Is there a benefit one way or another?

it’s just for safety incase the info’s missing

No, you can do whatever you feel fit. I like to make things fool proof.

1 Like