Calculating time until wake-up time (input_datetime)

Hey all,

I am hoping someone can help me with this. I am trying to adjust an input_datetime, based on what time I go to bed.

I have an input_datetime allowing me to set my wake-up time:

input_datetime:
  wakeup_time:
    name: Wake-up Time
    has_time: true

What I am trying to do with an automation, which is triggered when I got to bed (a bayesian sensor changes state to true) is to check if there are at least 7 hours between now and the set wake-up time.

The best way I am guessing is use a UNIX timestamp

{{ as_timestamp(now()) }}

and substract that from the wake-up time and then convert to hours. The problem is that I don’t know how to convert the value of the wake-up time, which is something like ‘07:00:00’ to a UNIX timestamp as it does not contain a date, just hours.

Can anyone help?

Thanks in advance!

While the conversion of your input_datetime to a timestamp with date is simple(ish):

{% set d = now().strftime("%Y-%m-%d ") %} # todays date as a timestamp
{% set wakeup_with_date = strptime(d + states('input_datetime.wakeup_time'), '%Y-%m-%d %H:%M:%S').timestamp() %}

You may run into a problem as you are adding today’s date to the input_boolean when it could be tomorrow’s date that is required - i.e. if you go to bed before midnight and you want to wake tomorrow morning. You would need to add 86400 seconds to the timestamp if tomorrow’s date is required.

If you always go to bed before midnight just add the 86400 seconds to the wakeup_with_date formula.

If you sometimes go to bed after midnight it gets trickier. Easiest way I can think of would be this test:

{% set timestamp_no_date = (now().second + (now().minute * 60) + (now().hour * 3600)) %}
{% if state_attr('input_datetime.wakeup_time', 'timestamp') >= timestamp_no_date >= 0 %}

This tests if the time now (with no date) is between your wakeup time and midnight. if it is don’t add 86400 seconds to the tmestamp.

Keep in mind I’m no expert at this, it is untested and there could be an easier way.

Why not just add - for the background calculations - e.g. 6h to either timestamp, the going-to-bed time as well as the alarm time?
Then you can always subtract the former from the latter and get the right value - unless you go to bed before 6pm. If that happens regularly just use a larger offset.