Search code examples
jsontimestampjinja2iso8601

How to convert JSON timestamp to time using Jinja?


I have this simple JSON:

{
     "ts": "2022-07-17T09:24:21.840227"
}

and I would like to know what date it is using Jinja.

I tried these two variations:

  • {{ ts | iso8601_to_time | datetimeformat('%a, %B %d %Y, %H:%M:%S') }}
    
  • {{ ts | timestamp_to_time | datetimeformat('%a, %B %d %Y, %H:%M:%S') }}
    

but both of them are throwing actual time.

I would expect something like this:

Sun, July 17 2022, 09:24:17

How can I achieve this format?


Solution

  • Ok, I figured it out in a meanwhile:
    {% set myDate = ts | split('.') %}
    {% set myDateFinal = myDate[0]+'Z' %}
    {{ myDateFinal | strtotime("yyyy-MM-dd'T'HH:mm:ssXXX") | datetimeformat('%a, %B %d %Y, %H:%M:%S') }}


    Basically:

    • Split by "." sign (makes array of what is left[0] and right[1] from dot)
      [2022-07-17T09:24:21, 840227]
    • Look at the first (left) part and add "Z" sign
      2022-07-17T09:24:21Z
    • Do some magic

      Done!