Template error with timestamp

Hi! I have a template to get the date and time when the sun is rising and sets.
The log shows this:


Last logged: 5 juni 2022 16:54:08

* Error while processing template: Template("{{ as_timestamp(strptime(state_attr("sun.sun", "next_rising"), "")) | timestamp_custom("%Y-%m-%d %H:%M:%S") }}")
* Error while processing template: Template("{{ as_timestamp(strptime(state_attr("sun.sun", "next_setting"), "")) | timestamp_custom("%Y-%m-%d %H:%M:%S") }}")

Anyone have a solution?

Regards
Thomas

You’re providing "" as a default for strptime that normally returns a datetime. Which is causing as_timestamp to fail to convert, which has no default. So that’s where your error is. Keep in mind, if you provide another bad default to as_timestamp, you’ll also need to provide a default to timestamp_custom.

or you could simply provide a datetime as the default for strptime instead of "". Something like today_at() which will default the result to midnight. Or now() which will default the template to the current time.

What Petro said… Use the template editor to debug these things also.

Plugging in your template gives the error:

ValueError: Template error: strptime got invalid input ‘2022-06-06T21:17:21.329097+00:00’ when rendering template ‘{{ as_timestamp(strptime(state_attr(“sun.sun”, “next_rising”), “”)) | timestamp_custom("%Y-%m-%d %H:%M:%S") }}’ but no default was specified

Which points you to what Petro said above - as well as telling you that the reason it is trying to get the default is because it’s already in the correct time format to apply as_timestamp.

Thus:

{{ as_timestamp(state_attr('sun.sun','next_setting')) | timestamp_custom('%Y-%m-%d %H:%M:%S') }}

Will give you the correct result, but you still should fix the default if you use strptime

That will fail at startup if next_setting isn’t populated, same issue as above. Need to provide a default when teh attribute is none or doesn’t exist. I can’t remember if next_setting is a dt object or string. Ether way, the way to solve it is to add a default.

Ah yes - all depends on what loads first.

A dt object I believe - at least as_timestamp accepts it.

So:

{{ as_timestamp(state_attr('sun.sun','next_rising'),now()) | timestamp_custom('%Y-%m-%d %H:%M:%S') }}

would work. How often does sun.sun update? Would it load the correct value eventually?

Yes, it would be instant. Startup is a race condition for all integrations because HA is async. So the template could load before sun and it would cause the error and never update again. So you guard against that with a default. When sun loads properly, the state will reflect it instantly.

1 Like

Thanks all. I changed and now it works.

Thomas