Sanity check for "as_timestamp"

Can the template extension “as_timestamp” mentioned here be updated to not cause an exception if the parameter is not a valid timestamp? Perhaps just print “Never” or “Error” instead?

Many templates using this extension spam the logs with errors since the states they are parsing at startup are not yet properly defined: here, here, and here.

I’ve put a ‘if defined’ check before, but apparently at startup, the state attribute is defined just not yet set to a valid datetime.

I think this feature request is actually “restore states”, not “sanity check”.

I think restoring states on restart is coming very soon to Home Assistant.

You can set initial values for things to get around some of these errors.

Actually, restore states won’t help my particular case. I have a sensor to display the startup time of HA which uses a template and the as_timestamp function. It just references the last_triggered attribute of an automation that is triggered by homeassistant start. The problem is that the sensor tries to access the attribute before the automation has run. I’ve scripted around it by doing a lot of ‘if defined’ variable checks, but it seems like it would be easier if as_timestamp() cleanly handled by input instead of throwing exception.

1 Like

I am unsure this can fixed by returning “Error”. A timestamp is a data type (an integer), not a string, and should not return other than that, for example:

{{ as_timestamp(strptime(states.sun.sun.attributes['next_setting'], "%Y-%m-%dT%H:%M:%S+00:00")) | timestamp_custom("%H:%M") }}

Perhaps it could be made to return None, in any case you are right I think it shouldn’t raise an Exception.

Other template extensions, like float, round, and other datetime ones, avoid raising exceptions. I also think the exception should not be raised here.

On your behalf, I have submitted a PR to get this fixed: .


Thanks for the clarification. And wow, @jjmontesl is on it! nice!