Cheknov
Cheknov

Reputation: 2082

How to change the Django date time format in a string

Given a long string (serialized Django object) how can we search all the timestamps and replace them with the correct format (dd/mm/YYYY HH:MM)

Example date (from the given example): 2022-01-11T16:49:43.897 Desired date time format: 11/01/2022 16:49

What I've tried so far:

@login_required
def my_view(request):
    response = dict()
    if request.method == 'GET':
        files = Files.objects.all().filter(user=request.user)
        for fhr in files:
            fhr.updated = fhr.updated.strftime("%d/%m/%Y %H:%M:%S")
        data = serialize("json", files)
        return HttpResponse(data, content_type="application/json")
    return HttpResponse('')

Basically I tried to edit the queryset with the correct format strftime("%d/%m/%Y %H:%M:%S") so that when I serialize the QuerySet into JSON data data = serialize("json", files) the string (data) contains the date and time in the correct format but it did not work.

So now I think that the only chance is to edit directly the string and replace those timestamps with the timestamps in the correct format.

Upvotes: 0

Views: 486

Answers (1)

Alex Petul
Alex Petul

Reputation: 26

The easiest way is to specify encoder class in serialize function. Refer to the documentation.

import typing

from datetime import datetime
from django.core.serializers.json import DjangoJSONEncoder


class DatetimeJSONEncoder(DjangoJSONEncoder):

    def default(self, o: typing.Any) -> str:
        result = super().default(o)
        if isinstance(o, datetime):
            result = o.strftime("%d/%m/%Y %H:%M:%S")
        return result

data = serialize("json", files, cls=DatetimeJSONEncoder)

Upvotes: 1

Related Questions