AppDeamon and Timezone : Critique my code

Good morning all !

Some context

I have a pretty nice “Wake-up” automation:
It controls lights, heaters, pre-heat my coffee machine, plays some music… etc

For a long time, my wake-up time was fixed.
So I wan just controlling it by a single input_datetime.wake_up_time and I was happy with it.

Now that I am hybrid remote working, my wake-up time changes almost daily.

So this weekend, I tackled an item that was on my to-do list for a very long time :
Sync the wake-up time of the alarm of my phone to the input_datetime I am using on Home-Assistant.

And it’s working yay :tada:

  1. Changing Wake-up time on my phone
  2. Home-Assistant notifies me
  3. I press the actionalble button on the notification
  4. input_datetime.wake_up_time is updated

Problem

I really don’t like the code I wrote.
It’s ugly, complex… I am almost certain I totally missed something.

The problem is about transforming the data I am receiving from the Home Assistant companion app representing the datetime of the alarm into a local time that I can use to change my input_datetime

When I started this automation I thought :

Easy peasy, ApppDeamon provides dozen of time helpers, I am just going to open the doc and I’ll be done in 30 minutes…

But yay… I am wrong.

My Current Code + Explanations

# The listener 

self.listen_state(self.callback_jl_phone_alarm_changed, "sensor.pixel6_prochaine_alarme")


# The callback
def callback_jl_phone_alarm_changed(self, entity, attribute, old, new, kwargs):
  if new != "unavailable":
    jl_home_alarm_time = (self.convert_utc(new) + datetime.timedelta(minutes = self.get_tz_offset())).time()
    # Do stuff

Explanations:

sensor.pixel6_prochaine_alarme state is a string

  • So new looks like 2022-01-10T05:30:00+00:00

  • I first convert it into a datetime: self.convert_utc(new)

  • The I add the delta related to my timezone + datetime.timedelta(minutes = self.get_tz_offset())

  • Then I take the time of all that and ignore the date : (...).time()

It’s super ugly, what am I missing?

How do I transform 2022-01-10T05:30:00+00:00 into 06:30:00 (local time) more simply ?

Thx a lot !!

Use the astimezone() method of the datetime object.

self.convert_utc(new).astimezone().time()