Formatting UTC time to local time and calculating "minutes until ..."

Hello,

I want to have Home Assistant display the number of minutes until the next bus arrives.

I have a sensor sensor.bus_estimated and its value is in UTC such as

2018-03-03T23:07:49Z

There’s two things I’d like to do

  1. Convert that to local time, such as 9.49am
  2. Calculate in how many minutes that is (eg., if the time is 9.45am, then it should calculate “4 minutes”)

The next parts to this will be if the bus is more than an hour away, then instead of displaying “in xxxx minutes” it would display the time.

Any help with formatting time is appreciated!

1 Like

Use a template to calculate the minutes until your sensor:

{{((as_timestamp(states.sensor.my_sensor.state)-as_timestamp(now()))/60) | int }}

Use a template to display the current time:

{{as_timestamp(states.sensor.my_sensor.state) | timestamp_custom("%X")}}
2 Likes

{{ your_zulu_time_thingo | timestamp_local }} woks to display in local time too.

1 Like

To display hours and minutes:

{%set sec = as_timestamp(states.sensor.my_sensor.state)-as_timestamp(now())%}
{%set hr = (sec / 3600) | int%}
{%set min = sec / 60 - hr * 60%} 
{% if hr > 0 %}
  {{"%d:%02d" % (hr, min)}}  
{%else%}
  {{min | int}}
{%endif%}
5 Likes

Thank you - so quick! I’ve been Googling and making a mess of this.

Treno your solution is perfect :grinning: Thanks Tom as well :smiley:

Just want to highlight that as_timestamp works for converting string ISO 8601 time in UTC (ending with Z) into local time perfectly. This cannot be found in the docs, so thanks heaps!

1 Like

Apologies for hijacking the thread, I have a Template sensor to display the last time a snapshot was taking using the google drive plugin. This displays in UTC.

Really hoping there is an easy way to display in my local time in Australia. Also, hoping to customise the output, may it shorter like DD/MM HH:MM etc.

Current output is way too long:

2019-09-26T21:18:28.596753+00:00

Any tips appreciated :slight_smile:

Linton

      last_snapshot:
        value_template: "{{ state_attr('sensor.snapshot_backup', 'last_snapshot') }}"
        friendly_name: 'Last Snapshot'