Dates calculation

Hi everyone !

I need some help to do some calculation with dates.
I have an event in google calendar with a start date & time and an en date & time.
I want to do an automation which :

  • Test if the start date is lesser or equal than today (date_start =< date_today)
  • Test if the end date is different than today (date_end != date_today)
  • Test if date & time end date is lesser than 24h (datetime_end - datetime_now < 24h)

If all is true > turn a switch off
If one is not true > do nothing

How can I write this ?
I’m a bit lost ^^

Thx for your help

The trick to date math is to convert the dates to timestamps.
Here is a quick example:

{%set start_date = as_timestamp(“2017-05-13 05:20:37”)%}
{{start_date}}
{%set date = as_timestamp(now()) %}
{{date}}

{%if start_date < date%}
LESS
{%else%}
NOT LESS
{%endif%}

{%if start_date != date%}
NOT EQUAL
{%else%}
EQUAL
{%endif%}

{%set diff = (date - start_date)/3600%}
{%if diff<24%}
LESS THAN 24 HOURS
{%else%}
NOT LESS THAN 24 HOURS
{%endif%}

1 Like

Hi treno,

Thx for your help.
Just some questions… :slight_smile:
When you compare the as_timestamp, will it compare only the date ? or date + time ?
When I said :

Test if the start date is lesser or equal than today (date_start =< date_today)

I meant that the date only of the datetime return by google has to be lesser or equal to today’s date (not the time)
And what’s the sign to test lesser or equal ? “<=” ?

The 2nd test should check if the end date (not the time) is different than today’s date.

Thx !
amans

I think I managed to do what I wanted :slight_smile:

How to turn off my water heater when I’m on holidays
My water heater turn on/off automatically when energy is cheaper.
So I turn it off just after it has been turn on.

- alias: Water Heater Toggle trigger: - platform: time after: '07:03:00' - platform: time after: '23:03:00' condition: condition: and conditions: - condition: state entity_id: 'switch.fibaro_system_fgs212_switch_3kw_switch_2_0' state: 'on' - condition: state entity_id: 'calendar.g_cal_y_hld' state: 'on' - condition: template value_template: '{{ as_timestamp(states.calendar.g_cal_y_hld.attributes.start_time) <= as_timestamp(now()) and as_timestamp(states.calendar.g_cal_y_hld.attributes.end_time) != as_timestamp(now()) and ((as_timestamp(states.calendar.g_cal_y_hld.attributes.end_time) - as_timestamp(now())) / 3600 ) > 24 }}' action: service: switch.turn_off entity_id: switch.fibaro_system_fgs212_switch_3kw_switch_2_0

I hope it’s gonna work
Not sure it’s gonna fit all possibilities ^^

1 Like