Appdaemon script to get Percentage of year complete

My kids challenged me to get a percentage progress of the year complete (similar to the twitter account @ProgressBar201X). It’s my first appdaemon sensor, but thought I’d share here.

import appdaemon.plugins.hass.hassapi as hass
from datetime import datetime, time, timedelta

#
# Simple sensor to capture the percentage of the year complete
# 

class YearComplete(hass.Hass):

  def initialize(self):
    # update the sensor every day at 00:01
    runtime = time(0, 1, 0)
    self.run_daily(self.update_sensor, runtime)
    
    # update immediately on launch
    self.update_sensor()
     
  def update_sensor(self, **kwargs):
    # get the current year
    y = datetime.now().year
    
    # work out the last day of the year (go to 1/1/current_year + 1) and take a day off
    ny = datetime(y+1, 1, 1) - timedelta(days=1)
    num_days = ny.timetuple().tm_yday
    
    # get current day of year
    current_day = datetime.now().timetuple().tm_yday
    day_percent = int(float(100.0 / num_days) * current_day)
    
    # set sensor.year_complete
    self.set_state('sensor.year_complete', state=day_percent, attributes={'unit_of_measurement':'%'})
    self.log('Year is ' + str(day_percent) + '% complete')

Looks like this as a Lovelace entity, will change to a bar chart eventually!

image

1 Like

:slight_smile:

Now how about

sensor:
  - platform: command_line
    command:  expr  $(date +%j) \* 100 / 365
    name: Percentage of Year Gone
    unit_of_measurement: '%'

Notes:

  1. No account taken of leap year.
  2. May need to quote the command.

The command line is something I need to look into as I’m not overly familiar with whats possible.

I’ll work out what to do with the leap year.

The command line can be very powerful if there’s already a Linux command that does what you need. Usually, at least for me, it doesn’t do exactly what I need. At the very least, I need to massage the data some which can be done with more command line work and pipes a lot of the time. But, at that point, for me, my Python-Fu is much stronger than my sed/awk/grep/jq/bash-Fu. So I’d end up writing it in Python and AppDaemon is a lot easier than running Python as a command line script (though that is an option, too).

My aim was not to set up a competition as to the right/wrong/best way, merely to draw attention to possibilies and see if I could do it :slight_smile:

1 Like