Save time event triggered for recall? (ie Locked door at 06 18 pm)

Evening,

Could someone point me in the right direction? I’m trying to save when my door is locked by using an automation to run a python script to save the time my “lock” was last triggered:

from datetime import datetime
now = datetime.now()
timenow = now.strftime('%I %M %p')
hass.states.set('sensor.locktime', timenow)

If I replace:

hass.states.set('sensor.locktime', timenow)

with

print(timenow)

It prints exactly what I want (ie 06 18 PM).

My lock sensor is basically a door sensor that is activated when the bolt is thrown (link here).

I just can’t get the python script to create the state. I appreciate it’s probably to do with what a state can be saved as. I could get it working with datetime.now() but that was not a usable value as I also want to call it from a custom Alexa skill through an intent script so I need it to read “06 18 PM” and not “18:18:179939393”.

I have an input_datetime defined for each door I’m tracking.

The automation for my garden gate looks like this:

- alias: Last Gate Opened Date and Time
  trigger:
    platform: state
    entity_id: sensor.gardengate
    from: 'off'
    to: 'on'
  action:
    - service: input_datetime.set_datetime
      data_template:
        entity_id: input_datetime.gardengate_last_opened
        time: '{{ (as_timestamp(now()) | timestamp_custom("%H:%M:%S", true)) }}'
        date: '{{ (as_timestamp(now()) | timestamp_custom("%Y-%m-%d", true)) }}'

For all the other doors, I was able to template it into one automation:

- alias: Last Door Opened Date and Time
  trigger:
    platform: state
    entity_id: binary_sensor.front_door, binary_sensor.back_door, binary_sensor.balcony_door, binary_sensor.downstairs_door
    from: 'off'
    to: 'on'
  action:
    - service: input_datetime.set_datetime
      data_template:
        entity_id: input_datetime.{{ trigger.entity_id[14:] }}_last_opened
        time: '{{ (as_timestamp(now()) | timestamp_custom("%H:%M:%S", true)) }}'
        date: '{{ (as_timestamp(now()) | timestamp_custom("%Y-%m-%d", true)) }}'

Thank you didn’t even know there was an input_datetime.

This information is all in your database.

How do you recall the information?

Something in this component may work https://www.home-assistant.io/components/sensor.history_stats/

Or use a command line sensor with an sql query.

EDIT, I knew I’d seen it https://www.home-assistant.io/components/sensor.sql/