Problem with datetimes in template

I cannot figure out what I am doing incorrectly when I'm trying to compare two values. The following code shows the code I'm working on (with some debugging added):

1 {% set next_midnight = state_attr('sun.sun', 'next_midnight') | as_datetime %}
2 next_midnight = {{ next_midnight }} ({{next_midnight | typeof}})
3 {% for attr in states.sun.sun.attributes %}
4    checking {{ attr }} : {{ states.sun.sun.attributes[attr] }} : {{ state_attr('sun.sun', attr)}}
5    {% set value = state_attr('sun.sun',attr) | as_datetime %}
6    value = {{ value }} ({{ value | typeof}})
7    {{ value , next_midnight }}
8  {% endfor %}

lines 2 and 6 show that the items I wish to compare (value and next_midnight) are both datetimes.
line 7 shows the values of both items.
However, change the comma (,) in line 7 to a less than (<) then code fails with
TypeError: '<' not supported between instances of 'NoneType' and 'datetime.datetime'
I can't figure out why this is happening when value and next_midnight are both datetimes.

Any help would be appreciated

There are a number of attributes of sun.sun that don't return datetimes... you need to filter those out.

Here are a couple of approaches...

{%- set next_midnight = state_attr('sun.sun', 'next_midnight') | as_datetime %}
{% for (attr,val) in states.sun.sun.attributes.items() if not val|is_number %}
{%- set val_dt = val|as_datetime%}
  {%- if val_dt is not none %}
    {{ val_dt < next_midnight }}
  {%- endif %}
{% endfor %}
{%- set next_midnight = state_attr('sun.sun', 'next_midnight') | as_datetime %}
{{ states.sun.sun.attributes.values()
| reject('is_number')
| map('as_datetime') | reject('eq', none)
| select('<', next_midnight)   
| list }}

... if you clarify what your goal is, someone can probably give you a more specific answer.

The forest for the trees....
As soon you posted that, I saw the issue.
Thank you, so much