SNMP uptime with device_class timestamp

I want to query the uptime of one of my servers via SNMP and want to create a timestamp device.

The resulting sensor appears always as unavaliable.

What am I doing wrong?

sensor:
  - platform: snmp
    name: Serverraum donna Uptime
    unique_id: serverraum_donna_uptime
    host: 10.0.3.40
    baseoid: 1.3.6.1.2.1.1.3.0
    accept_errors: true
    device_class: timestamp
    # unit_of_measurement: seconds
    value_template: >
      {% set uptime =  value / 100 | int %}
      {% set timestamp = (as_timestamp(now()) - (uptime | int)) %}
      {{ as_datetime(timestamp).isoformat() }}

Best regards
Chris

Are you sure that value is a simple, numeric data type?

The example from the docs implies that it may not be. You may want to set the value template to just return value without any modifications so you can see the type of value normally returned, then update the template accordingly.

I’m a bit overwhelmed with this topic, so I’m not sure.

SNMP - Home Assistant lists this example to get a printer uptime:

# Example configuration.yaml entry
sensor:
  - platform: snmp
    name: "Printer uptime"
    host: 192.168.2.21
    baseoid: 1.3.6.1.2.1.1.3.0
    accept_errors: true
    unit_of_measurement: "minutes"
    value_template: "{{((value | int) / 6000) | int}}"

My goal is to have an SNMP sensor that works and looks like the uptime sensor from the system monitor integration. From my understanding I need to convert the ticks that are fetched via SNMP to seconds. ANd to get the last boot time I must substract it from the timestamp of now(). And for the device_class timestamp this has to be an object in ISO time format.

Do you have any other segestions?

EDIT: WHen I just ooutput the value, I get 44865222 which seams reasonable.

Reasonable for seconds, milliseconds, or some other unit?

Assuming value is being returned in milliseconds:

sensor:
  - platform: snmp
    name: Serverraum donna Uptime
    unique_id: serverraum_donna_uptime
    host: 10.0.3.40
    baseoid: 1.3.6.1.2.1.1.3.0
    accept_errors: true
    device_class: timestamp
    value_template: >
      {% set uptime = (value | int / 1000) %}
      {{ now() - timedelta(seconds = uptime) }}

Thanks for your response!

With your code home assistant complains: ValueError: Invalid datetime: sensor.serverraum_donna_uptime has timestamp device class but provides state 2024-03-20 19:09:13.040710+01:00:<class ‘str’> resulting in ‘‘str’ object has no attribute ‘tzinfo’’.

I tried several things to convert the date to iso format but everything results in an unavaliable sensor. I find this date and time stuff really confusing.

Time stuff can get annoying… there are so many different functions, methods, and formats.

Try:

{% set uptime = (value | int / 1000) %}
{{ (now() - timedelta(seconds = uptime)).isoformat() }}