Convert HH:MM from UTC to local

Hi,

I have searched and there are similar questions to mine (eg: here) but mine is a little different.

I have managed to get a time off a website in the format HH:MM (eg: 09:30) which I know is UTC. How can I convert that to local time?

I’ve tried using timestamp_local, but get invalid input.

  1. What is the correct format for a time-only input for timestamp_local (is there one)?
  2. How can I get it from HH:MM?

Have a look at this library, created by our well known community member @petro

I’m pretty sure that you’ll find what you need, and if not, you can ask him for an update :wink:

1 Like

much appreciated! I will take a look later this morning :+1:

A time in a format such as HH:MM isn’t a valid UTC format for converting. You will see an example on this page - Date and Time Formats

1 Like

Thanks.

That probably explains why hh:mmZ, Thh:mmZ, hh:mm+01:00 or Thh:mm+01:00 didn’t work when I tried them (should have mentioned that in my opening post).

In the following template, replace sensor.website_utc with the entity_id of your entity that reports UTC time in HH:MM format.

{{ '{} {}+00:00'.format(now().date(), states('sensor.website_utc')) 
  | as_datetime | as_timestamp | timestamp_custom('%H:%M') }}

To test the template, copy-paste it into the Template Editor.


Here’s another way to do the same thing:


{% set (h,m) = states('sensor.website_utc').split(':') | map('int', 0) %}
{{ utcnow().replace(hour=h, minute=m, second=0) 
  | as_timestamp | timestamp_custom('%H:%M') }}
1 Like

wow - that’s awesome - thanks!

as_local and '{} {}+00:00'.format(now().date() are both new to me. Do you know where I can find out more about them (for my own education)?

edit:
OK, got it - played with it in templates and worked out what they call mean - fantastic stuff.

there’s about 800 ways to do this.

{{ ((now().date() ~ ' ' ~ states('sensor.website_utc') ~ "+00:00") | as_datetime | as_local).strftime('%H:%M') }}
1 Like

format is a method of strings (in python).

as_local is a Jinja2 filter described in the documentation here. However, I removed it from the template example because it wasn’t needed.

1 Like

Thanks!
Do the ~ mean concatenate? How is it different from ‘+’?

yes, it ensures everything that’s “added” is a string. + does not do that

1 Like

fantastic - thanks for the pointer and edit :+1:

I think I need to learn Python - have always intended to, but never got round to it …until HA :slight_smile:

That’s not python, that’s jinja. Python does not have the ~ operator

Got it - thanks!

(I always thought jinja was a part of Python)

Jinja is based on python. The ~ operator from python is not usable in jinja because jinja uses it for concatenating strings. The ~ operator in python is seldom used. I don’t even think its covered in the python docs but it’s mentioned.

you can read up on the python version here

1 Like

I really appreciate all the help from everyone. Lots to research and learn now :+1: