Return Response values objects model with time zone

Hello,
I have some problem when building rest api to return data from model query. Datetimefield field return me value in UTC = 0 and how can I trust table with utc+7.
data I return as json and rename model fields.
data = { "code": 0, "msg": "", "data": list(objpagnation.values('id', 'membercount', 'code', username =F('user__username'), status=F('user__is_active'), roles=F('role__name'), last_time=F('user__last_login'), create_time=F('created_date'), update_time=F('updated_date'))), "count": len(objs) }
fields last_time returns as: 2024-09-10T11:00:48.279Z
and I want: 2024-09-10 18:00:48.279

You need to post your models here.

I think that you should convert the datetime fields in target time zone and then format the datetime to the desired string format and trim the microseconds to milliseconds.

Something like that:

from django.db.models import F
from django.utils import timezone
import pytz

# Define your target time zone 
target_tz = pytz.timezone('Asia/Bangkok')

# Fetch the data
objs = objpagnation.values(
    'id', 
    'membercount', 
    'code', 
    username=F('user__username'), 
    status=F('user__is_active'), 
    roles=F('role__name'), 
    last_time=F('user__last_login'), 
    create_time=F('created_date'), 
    update_time=F('updated_date')
)

# Convert datetime fields to the target time zone
data_list = []
for obj in objs:
    obj['last_time'] = timezone.localtime(obj['last_time'], target_tz).strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
    obj['create_time'] = timezone.localtime(obj['create_time'], target_tz).strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
    obj['update_time'] = timezone.localtime(obj['update_time'], target_tz).strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
    data_list.append(obj)

data = {
    "code": 0,
    "msg": "",
    "data": data_list,
    "count": len(objs)
}

class Agent(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    code = models.IntegerField()
    role = models.ForeignKey(Role, on_delete=models.CASCADE)
    created_date = models.DateTimeField(blank=True, null=True)
    updated_date = models.DateTimeField(blank=True, null=True)
    created_user = models.CharField(max_length=50, blank=True, null=True)
    updated_user = models.CharField(max_length=50, blank=True, null=True)

    class Meta:
        managed = True
        db_table = "agent"

    def __str__(self):
        return self.user.username

can you help me i make it + timedelta 7 hour but it is not good solution

data = {
    "code": 0, "msg": "",
    "data": list(objpagnation.values('id', 'membercount', 'code', username =F('user__username'), status=F('user__is_active'), roles=F('role__name'), last_time=F('user__last_login'), create_time=(F('created_date') + timedelta(hours=7)), update_time=(F('updated_date') + timedelta(hours=7)))),
    "count": len(objs)
}

I do not really understand what you are asking. What is your timezone?

my timezone is

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'Asia/Ho_Chi_Minh'

USE_I18N = True

USE_TZ = True

my Datetimefield return me datetime +7 → UTC +0 to variable

like this
obj.created_date = timezone.now() # 2024-09-15 12:00:00 TZ +7 print(obj.created_date) # -> 2024-09-15 05:00:00 UTC +0
i use annotate to create a field char and assign it = my datetimefiel + timedelta(hours=7) like this

objs = objs.annotate(create_time=Func(F('created_date') + timedelta(hours=7), Value('yyyy-MM-dd hh24:mi:ss'), output_field=CharField(), function='to_char'),
                             update_time=Func(F('updated_date') + timedelta(hours=7), Value('yyyy-MM-dd hh24:mi:ss'), output_field=CharField(), function='to_char'))

Ok… I guess that you want to automatically handle the timezone conversion.

from django.db.models import F, Func, Value, CharField
from django.db.models.functions import TruncSecond
from django.utils import timezone

objs = objs.annotate(
    create_time=Func(
        TruncSecond(F('created_date'), tzinfo=timezone.get_current_timezone()),
        Value('YYYY-MM-DD HH24:MI:SS'),
        function='to_char',
        output_field=CharField()
    ),
    update_time=Func(
        TruncSecond(F('updated_date'), tzinfo=timezone.get_current_timezone()),
        Value('YYYY-MM-DD HH24:MI:SS'),
        function='to_char',
        output_field=CharField()
    )
)

TruncSecond(F('created_date'), tzinfo=timezone.get_current_timezone()): This converts the UTC time stored in the database to your local timezone (Asia/Ho_Chi_Minh)

When you use this annotated queryset, create_time and update_time will be strings representing the datetime in Asia/Ho_Chi_Minh timezone.

And if you need to work with the datetime objects themselves (not strings), you can simply use:

from django.utils import timezone

obj.created_date.astimezone(timezone.get_current_timezone())

Thank you my work smoothly with this

I am glad it worked! Mark the post as solution in order to help others @itwebsa88