Date conversion

Hi,

I have a date string:

“1970-01-01 05:15:00”

How can I convert this to “05:15:00”

Why can’t I create this value_template:

{{ strptime('1970-01-01 05:15:00', "%H:%M:%S") }}

to get “05:15:00” ?

BR/Nicklas

{{ '1970-01-01 05:15:00'.split(' ')[1] }}

Thanks! Yes, I guess I can do like that but I would also like to learn how to use the strptime function.
I’m probably missing something obvious…

When using strptime you need to use a format string that matches the input. In this case your format string matches the time part, but not the date part. Note that strptime takes a string and converts it to a Python datetime object, so the format string tells it how to interpret the string, not how to format the “output.” You can then use the datetime’s time method to get the time portion. I.e.:

{{ strptime('1970-01-01 05:15:00', '%Y-%m-%d %H:%M:%S').time() }}

Or you could use its strftime method (which converts the other way, i.e., from a datetime to a string):

{{ strptime('1970-01-01 05:15:00', '%Y-%m-%d %H:%M:%S').strftime('%H:%M:%S') }}

Another way which converts first to a timestamp would be:

{{ as_timestamp('1970-01-01 05:15:00')|timestamp_custom('%H:%M:%S') }}

3 Likes

Thank you! :slightly_smiling_face: