I guess I was – or at least with attributes that represented the constituents of the timedelta. I can think of two ways to do this but both seem very non-pythonic:
- I can duplicate the code for calculating the timedelta in the template sensor where I need it because then the python timedelta object contains the days/seconds attributes (
billing_time_left.days
, and billing_time_left.seconds
). I did this in the template tool first to prove out the functionality but I was hoping to easily re-use the sensor values in the same way.
{%- set today = now().replace(tzinfo=None, microsecond=0) -%}
{%- set billing_day = strptime('{}-{}-21'.format(today.year, today.month),'%Y-%m-%d') -%}
{%- if as_timestamp(billing_day) - as_timestamp(today) <= 0 -%}
{%- if today.month == 12 -%}
{%- set billing_day = strptime('{}-01-21'.format(today.year+1),'%Y-%m-%d') -%}
{%- else -%}
{%- set billing_day = strptime('{}-{}-21'.format(today.year, today.month+1),'%Y-%m-%d') -%}
{%- endif -%}
{%- endif %}
{%- set billing_time_left = billing_day - today -%}
If today is: {{ today }}
Billing day is: {{ billing_day }}
Bandwidth left: {{ (350 - (states('sensor.wan_monthly_data_in')|float + states('sensor.wan_monthly_data_out')|float)/1e9)|round(4) }}
Time left: {{ billing_time_left }}
Bandwidth left per day: {{ (((350 - (states('sensor.wan_monthly_data_in')|float + states('sensor.wan_monthly_data_out')|float)/1e9)|round(4))/(billing_time_left.days + billing_time_left.seconds/86400)) | round(2) }}GB/day
This code works all together, and produces:
If today is: 2020-12-06 10:56:44
Billing day is: 2020-12-21 00:00:00
Bandwidth left: 291.2344
Time left: 14 days, 13:03:16
Bandwidth left per day: 20.02GB/day
- Alternatively, I can decompose the string into separate
days
and timestamp
values and manually calculate the floating point number of days remaining.
It just feels dirty to copy the entire block of code into a second sensor just to recalculate the timedelta object so I can use it again for another purpose.
Looking for guidance on how best to handle this. Also, I know you guys are much more efficient at logic blocks than I am so if you have suggestions on ways to tighten it up, I’m all ears! 