# Return Response values objects model with time zone

**URL:** <https://forum.djangoproject.com/t/return-response-values-objects-model-with-time-zone/34670>\
**Category:** Forms & APIs\
**Created:** [September 10, 2024, 11:48am UTC](https://forum.djangoproject.com/t/return-response-values-objects-model-with-time-zone/34670 "2024-09-10T11:48:41Z")\
**Posts on this page:** 8\
**Page:** 1

<div class="post-metadata">

**Author:** ![itwebsa88](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/itwebsa88/32/23813_2.png) [@itwebsa88](https://forum.djangoproject.com/u/itwebsa88)\
**Post date:** [September 10, 2024, 11:48am UTC](https://forum.djangoproject.com/t/return-response-values-objects-model-with-time-zone/34670/1 "2024-09-10T11:48:41Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![anefta](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/anefta/32/10649_2.png) [@anefta](https://forum.djangoproject.com/u/anefta)\
**Post date:** [September 11, 2024, 9:39am UTC](https://forum.djangoproject.com/t/return-response-values-objects-model-with-time-zone/34670/2 "2024-09-11T09:39:49Z")

</div>

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:

```auto
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)
}

```

---

<div class="post-metadata">

**Author:** ![itwebsa88](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/itwebsa88/32/23813_2.png) [@itwebsa88](https://forum.djangoproject.com/u/itwebsa88)\
**Post date:** [September 14, 2024, 3:31pm UTC](https://forum.djangoproject.com/t/return-response-values-objects-model-with-time-zone/34670/3 "2024-09-14T15:31:06Z")

</div>

> [@anefta](#):
>
> `last_time`

```auto
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

```auto
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)
}

```

---

<div class="post-metadata">

**Author:** ![anefta](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/anefta/32/10649_2.png) [@anefta](https://forum.djangoproject.com/u/anefta)\
**Post date:** [September 14, 2024, 10:42pm UTC](https://forum.djangoproject.com/t/return-response-values-objects-model-with-time-zone/34670/4 "2024-09-14T22:42:47Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![itwebsa88](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/itwebsa88/32/23813_2.png) [@itwebsa88](https://forum.djangoproject.com/u/itwebsa88)\
**Post date:** [September 15, 2024, 5:19am UTC](https://forum.djangoproject.com/t/return-response-values-objects-model-with-time-zone/34670/5 "2024-09-15T05:19:12Z")

</div>

my timezone is

```auto
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

```auto
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'))

```

---

<div class="post-metadata">

**Author:** ![anefta](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/anefta/32/10649_2.png) [@anefta](https://forum.djangoproject.com/u/anefta)\
**Post date:** [September 15, 2024, 8:39am UTC](https://forum.djangoproject.com/t/return-response-values-objects-model-with-time-zone/34670/6 "2024-09-15T08:39:50Z")

</div>

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

```auto
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:

```auto
from django.utils import timezone

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

```

---

<div class="post-metadata">

**Author:** ![itwebsa88](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/itwebsa88/32/23813_2.png) [@itwebsa88](https://forum.djangoproject.com/u/itwebsa88)\
**Post date:** [September 15, 2024, 12:48pm UTC](https://forum.djangoproject.com/t/return-response-values-objects-model-with-time-zone/34670/7 "2024-09-15T12:48:10Z")

</div>

Thank you my work smoothly with this

---

<div class="post-metadata">

**Author:** ![anefta](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/anefta/32/10649_2.png) [@anefta](https://forum.djangoproject.com/u/anefta)\
**Post date:** [September 15, 2024, 1:18pm UTC](https://forum.djangoproject.com/t/return-response-values-objects-model-with-time-zone/34670/8 "2024-09-15T13:18:43Z")

</div>

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