Can we make input_datetime tz aware?

I may not fully understand this, but I’ve been working with/studying datetime a bit now trying to build an automation, using an input_datetime as a storage slot for last_updated values for entities for later comparisons. I wanted to put both the UTC and LOCAL times in the Logbook for debugging, but it appears the input_datetime is ‘naive’ and has no tzinfo, so it is not easily converted using the standard supplied methods. Would it make sense to be able to make intput_datetime entites tz aware? It could be an option in the config, which would allow us to use the supplied methods.

Although, maybe I’m missing something in my template tests. I tried to do several variations of the following, which produced errors:

UndefinedError: 'str object' has no attribute 'tzinfo' with

{{ states('input_datetime.XXX').tzinfo() }} or

UndefinedError: 'homeassistant.helpers.template.TemplateState object' has no attribute 'tzinfo' with

{{ states.input_datetime.XXX.tzinfo() }}

I was trying to use .astimezone() to get local time from UTC, which is what states('input_datetime.XXX') produces.

EDIT: however, I just found that THIS works!

{{ states.input_datetime.XXX.last_changed.astimezone() }}

So what is stored in the object is just a string then?

Although, this:

{{ now() - as_datetime(states('input_datetime.XXX'))

produces this:

TypeError: can't subtract offset-naive and offset-aware datetimes

The state value of any entity is a string.

If the input_datetime contains a date and time this will convert it from a string to an offset-aware datetime object.

{{ as_datetime(states('input_datetime.test')).astimezone() }}

On a separate note, the value of any entity’s last_changed property is an offset-aware datetime object (and it’s in UTC).

2 Likes

Perfect! This is LOCAL time, right? I could never get this ‘concept’ to work, and I could swear I tried this rendition. I could never get as_datetime to work for anything, so I gave up on it. As you indicated, I was able to get the states.MY_ENTITY.last_updated.astimezone() to work, so I just converted it to LOCAL before storing it in the input_datetime and was then able to compare it successfully to the now() after converting both with as_timestamps(). I beat my head against a wall for hours.

BTW, where are the tz= parameters to astimezone() defined? If I wanted to designate Alaska, where would I find what to enter?

Thanks (again) for the assist! Maybe I should just start paying you for some tutoring. :wink:

You can compare the value of now() to an offset-aware datetime object (without first converting both to timestamps).

If Alaska is your local time then astimezone() will add the correct local timezone offset to an offset-naive datetime object (assuming Home Assistant’s timezone setting is correct).