Datetime to string to substract to (later) time

I would like to use the todo list to track duration of baby sleep. How can I convert the now datetime to string and add it to a todo item then restore it to substract the current time to get the duration between?

alias: baby-sleep
sequence:
  - if:
      - condition: state
        entity_id: input_boolean.baby_sleep_toggle
        state: "off"
    then:
      - service: todo.add_item
        metadata: {}
        data:
          item: "{{ now().strftime(\"%d/%m/%Y: %H:%M\") }}: Start sleep"
        target:
          entity_id: todo.baby
    else:
      - service: todo.add_item
        metadata: {}
        data:
          item: "{{ now().strftime(\"%d/%m/%Y: %H:%M\") }}: End sleep"
        target:
          entity_id: todo.baby
  - service: input_boolean.toggle
    metadata: {}
    data: {}
    target:
      entity_id: input_boolean.baby_sleep_toggle
mode: single
icon: mdi:cradle-outline

Why not put the datetime string in the due_datetime option?

service: todo.add_item
target:
  entity_id: todo.baby
data:
  due_datetime: "2024-04-22 19:00:00"
  item: Start sleep
  description: Fourth nap of the day.

As a template:

service: todo.add_item
target:
  entity_id: todo.baby
data:
  due_datetime: "{{ now().strftime('%Y-%m-%d %H:%M:00') }}"
  item: Start sleep
  description: Fourth nap of the day.

When you get todo items (using todo.get_items), the datetime will be presented as a string in ISO format which is very easy to convert to a datetime object using as_datetime.

todo.baby:
  items:
    - summary: "Start sleep"
      uid: 055bdc60-00f3-11ef-8262-0024e8c67f1f
      status: needs_action
      due: "2024-04-22T19:00:00-04:00"
      description: Fourth nap of the day.

That could work. I would also need to be able to reorder the todo list to make it last in at top or keep x last items because the todo list will become long quickly and require scrolling. I tried to do a for_each on list items I’ve put in a variable, but I get errors when trying to use that in the for_each loop.

You can use a template to sort the items by date and optionally limit the resulting list to fewer items. It can be done without a for loop.

If you simply want to display the items, you can use the ToDo List card