time data '2023-04-15T16:22:03.721461+05:00' does not match format "%Y-%m-%dT%H:%M:%S.%f+%Z'"

163 Views Asked by At

I get my data from drf as json and ther my datetime looks like:

              `'2023-04-15T16:22:03.721461+05:00'`

but i want show datetime in template like:

                `'15-04-2023 16:22'` 

so i use tamplatetag:

# app/templatetags/event_extras.py
@register.filter(expects_localtime=True)
def parse_iso(value):
    return datetime.datetime.strptime(value, "%Y-%m-%dT%H:%M:%S.%f+%Z'")

and html like:

{% load event_extras %}

<th>{{r.datetime|parse_iso}|date:'d/m/Y H:M'}</th>

but got this error: time data '2023-04-15T16:22:03.721461+05:00' does not match format "%Y-%m-%dT%H:%M:%S.%f+%Z'"

2

There are 2 best solutions below

0
Dima Chubarov On BEST ANSWER

Since the timezone in your test string is specified as an offset not as a timezone string, you have to parse it with %z format specifier, not %Z in your original post. Also you do not want to put the sign in the format string:

def parse_iso(value):
   return datetime.datetime.strptime(value, "%Y-%m-%dT%H:%M:%S.%f%z")

This would parse your string as

>>> parse_iso('2023-04-15T16:22:03.721461+05:00')
datetime.datetime(2023, 4, 15, 16, 22, 3, 721461, tzinfo=datetime.timezone(datetime.timedelta(seconds=18000)))

0
NixonSparrow On

Look at the last character in the string, it's probably ruining the convertion:

return datetime.datetime.strptime(value, "%Y-%m-%dT%H:%M:%S.%f+%Z'")