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'"
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)))