as imports are not allowed - ho do i do this? need to substract a datetime from another represented by string
To help you, you would need to tell us more about where you need this datetime conversion - Python Script, a custom component, maybe in a template (sensor)?
Also, it often helps if you could show us what you have already tried, for example configuration or code snippets (working or not).
take a look at the subject - it’s python
i have a string saved in var to keep current time for later comparison:
- service: var.set
data_template:
entity_id: var.ac1_fan_measure_start_time
value_template: "{{as_timestamp(states.sensor.time.last_changed)}}"
but when i use it from python - it is recognized as a string
now = hass.states.get('sensor.time').last_changed
measureStartTime = hass.states.get('var.ac1_fan_measure_start_time').state
i need to get the time diff between the two
Yeah, I read the subject, but couldn’t think of a place where you would use plain Python without the ability to import anything.
Since you insist that you are using Python, and I can see that you somehow got hold of the hass
object, I don’t see any reason why you should not also be able to import, for example:
from homeassistant.util import dt as dt_util
dt_util.utc_from_timestamp(float(measureStartTime))
I believe you mean this code is running in a HA python_script
, which indeed has a limited execution environment.
First, you’re not saving a datetime. You’ve first converted it to a timestamp, which is a number. And, of course, like the state of all entities in HA, no matter what type it starts as, it will be converted to a string.
I would suggest:
now = hass.states.get('sensor.time').last_changed.timestamp()
measureStartTime = float(hass.states.get('var.ac1_fan_measure_start_time').state)
delta = now - measureStartTime
python script (ac =1):
now = hass.states.get('sensor.time').last_changed.timestamp
measureStartTime = float(hass.states.get('var.ac%s_fan_measure_start_time' %(ac)).state)
logger.info('LSX: now=%s start=%s', now, measureStartTime)
diff = now - measureStartTime
logger.info('LSX: diff=%s', now)
this is the output of the log:
now=<built-in method timestamp of datetime.datetime object at 0x6d203f80> start=1570687681.015453
Error executing script: unsupported operand type(s) for -: 'builtin_function_or_method' and 'float'
Because you didn’t copy the code correctly. You missed the parentheses for the timestamp function.
sorry - fixed it and working now - great thx!