The error you're encountering indicates that the as_local filter is expecting a datetime object, but it's receiving a string instead. To fix this, you need to ensure that the times are properly parsed into datetime objects before converting them to local time.
Here’s how you can modify your code to handle this correctly:
-
Parse the times into datetime objects:
Use the strptime function to parse the times into datetime objects.
-
Convert the datetime objects to local time:
Use the as_local filter on the parsed datetime objects.
-
Convert the local datetime objects back to timestamps:
Use the as_timestamp function on the local datetime objects.
Here’s the updated code:
actions:
- variables:
sunrise: >-
{{ as_timestamp(as_local(datetime.fromisoformat(state_attr('sun.sun', 'next_rising')))) }}
sunset: >-
{{ as_timestamp(as_local(datetime.fromisoformat(state_attr('sun.sun', 'next_setting')))) }}
noon: >-
{{ as_timestamp(as_local(datetime.fromisoformat(state_attr('sun.sun', 'next_noon')))) }}
morning_phase_end: >-
{{ ((noon - sunrise) / 2) + sunrise }}
afternoon_phase_start: >-
{{ ((sunset - noon) / 2) + noon }}
Explanation:
datetime.fromisoformat(state_attr('sun.sun', 'next_rising')): This parses the ISO 8601 formatted string into a datetime object.
as_local(): This converts the datetime object to your local timezone.
as_timestamp(): This converts the local datetime object to a timestamp.
This should resolve the AttributeError and ensure that the times are correctly computed in your local timezone.