I’ve get a list of tidal heights using REST from an API consisting of datetime, height pairs where the datetime is in UTC. I want to find the height at a datetime that the user chooses, so they set an input_datetime helper. The user will set this in local time and the helper is not TZ aware. What is the cleanest way of converting the non-tz aware datetime to utc? I’ve got this but is sin’t working.
The REST sensor select:
I keep making mistakes with datetimes that are not tz_aware despite reading around the subject - there must be a best practice way of making them aware that I can re-use. Please can anyone spare a minute to educate me?
There’s no good practices here, you need to know how to convert the current time into UTC, then format a string and use that as the selection. In order to make things datetime aware in UTC, you have to use built-ins on the datetime object. This typically means you need programming experience dealing with datetime objects
In general in order to make things datetime aware in your local timezone, it’s as easy as | as_datetime | as_local. Getting UTC is a pain because there’s no as_utc filter. So you have to convert to your TZ then to utc using utcnow’s tzinfo.
{% set t = (states('input_datetime.date_time') | as_datetime | as_local).astimezone(utcnow().tzinfo) %}
{% set tstring = t.strftime('%Y-%m-%dT%H:%M:%SZ') %}
{{ value_json | selectattr('Datetime', 'eq', tstring) | map(attribute='Height') | first | default("Invalid Time") }}