Compare unix timestamp with current time and slowly dim lights if its less than 30 minutes away

Hello, I know there are many topics discussing unix timestamp conversions already, but I didn’t find the information I need for my purpose. I sucsessfully used the homeassistant-googletokenretriever from @chvancooten to get the next alarm from my Google Home Mini into Home Assistant.
It’s in the unix format (for example “1612944005000.0”). I now need a way to compare that timestamp to the actual time and trigger an action of some type to slowly dim my lights. I hope someone can help me.

1 Like

What entity is your timestamp stored in?

1 Like

It should be a sensor entity. The configuration looks like this:

platform: command_line
command: "curl --insecure --header \"cast-local-authorization-token: {{ state_attr('input_text.google_tokens', 'token_my-google-home') }}\" https://my-google-home:8443/setup/assistant/alarms"
name: Next Alarm
value_template: >
  {% set alarms = value_json.alarm|sort(attribute='fire_time') %}
  {% if alarms[0] is defined %}
    {{ alarms[0].fire_time }}
  {% else %}
    None
  {% endif %}

Ok you could try this:

trigger:
  platform: template
  value_template: "{{ states('sensor.next_alarm') | int - as_timestamp(now()) < 30*60 }}"

Or maybe as_timestamp(utcnow()), check in the developer tools template editor.

3 Likes

Thank you, the second one worked!

1 Like

Hi @tom2199! Great to hear my script is useful :slight_smile:

Looks like your question was answered, I also use something similar to show the alarm time in my interface. Additionally, I have the following binary sensor that checks if the alarm is (less than) 15 minutes away in order to trigger my wakeup light automation. Maybe it’s helpful :slight_smile:

- platform: template
  sensors:
    next_alarm_within15min:
      value_template: >
        {% if states('sensor.next_alarm') == "None" or states('sensor.next_alarm') == "unavailable" or states('sensor.next_alarm') == "unknown" %}
          False
        {% else %}
          {{ (states('sensor.next_alarm') | int / 1000) - (as_timestamp(states('sensor.date') ~ ' ' ~ states('sensor.time')) | int) < 990 }}
        {% endif %}
      friendly_name: Next alarm within 15 minutes
      icon_template: 'mdi:alarm'
      delay_on:
        seconds: 90

Quite ugly, but it works!

1 Like

Thank you for your script! And thanks for chiming in, I appreciate it!

1 Like