Conditional timestamp_custom

Hi,

I’m using a custom_timestamp in a sensor to show when the front door was last opened:

as_timestamp(states.automation.tur_geschlossen.attributes.last_triggered) | timestamp_custom("%H:%M Uhr (%d.%m.)

But I only want to show the date ("%d.%m.") when the door was opened yesterday or earlier.

Is it possible to change the formatting depending on when the door was last opened?

{% set t = as_timestamp(states.automation.tur_geschlossen.attributes.last_triggered) %}
{% set fmat = "%d.%m." if now().timestamp() - t > 86400 else "%H:%M Uhr (%d.%m.)" %}
{{ t | timestamp_custom(fmat) }}

That’s almost what I’m looking for, but is it possible to check if it was opened actually yesterday and not more than 24 hours ago? Currently it’s 2:25pm here, the door was opened three hours ago, but it still shows the date.

ah

{% set t = as_timestamp(states.automation.tur_geschlossen.attributes.last_triggered) %}
{% set n = now().replace(hour=0).replace(minute=0).replace(second=0).replace(millisecond=0).timestamp() %}
{% set fmat = "%d.%m." if t < n else "%H:%M Uhr (%d.%m.)" %}
{{ t | timestamp_custom(fmat) }}

Thank you! For some reason replace(millisecond=0) isn’t working, so I had to remove it. Also it should be t > n instead of t < n. Here’s the final version:

{% set last_opened = as_timestamp(states.automation.tur_geschlossen.attributes.last_triggered) %}
{% set current_day = now().replace(hour=0).replace(minute=0).replace(second=0).timestamp() %}
{% set time_format = "%H:%M Uhr" if last_opened > current_day else "%H:%M Uhr (%d.%m.)" %}
{{ last_opened | timestamp_custom(time_format) }}

Well yeah, because you inverted the format output from yesterdays date to today’s hour/time… In regards to your original post < was the correct method.

It should be microsecond=0, typo on my part

1 Like

Here’s an interesting thing: The output seems to get cached. It always shows the time without the date, even the next day. When I restart Home Assistant, the date appears. How can this be?

You gotta add an entity_id that updates periodically to the entity_id: field. Something like sensor.time.