-1

I want to change the timezone of my django project to Asia/Karachi. I have added this in my settings.py file:

TIME_ZONE = "Asia/Karachi"

Time zone of my postgres is also set to Asia/Karachi. But still when I create the objects, the time zone of DateTimeField is set to UTC.

class MyClass(models.Model):
    name = models.CharField(max_length=64)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self) -> str:
        return self.name

Now when I create the object of MyClass, created_at and updated_at are storing Time with UTC timezone. Why is this so and how can I fix it? Edit: In my drf interface, I can see the time zone in Asia/Karachi. But when I check time zone in shell, it gives time zone in UTC. enter image description here

In python shell: enter image description here

Waleed Farrukh
  • 205
  • 1
  • 10
  • The Second Note might helpful in this link, https://docs.djangoproject.com/en/4.1/ref/models/fields/#django.db.models.DateField.auto_now_add – Shakeel Afridi Feb 15 '23 at 12:59
  • 3
    This is by design. See the first sentence of the [timezone documentation](https://docs.djangoproject.com/en/dev/topics/i18n/timezones/): "When support for time zones is enabled, Django stores datetime information in UTC in the database, uses time-zone-aware datetime objects internally, and translates them to the end user’s time zone in templates and forms." – Kevin Christopher Henry Feb 15 '23 at 13:11
  • Your output looks like things are working exactly as they should. You have UTC times in your database and they're translated to the Karachi TZ when outputting. – AKX Feb 15 '23 at 13:25

1 Answers1

0

In settings.py file, you can set the TIME_ZONE

TIME_ZONE = 'Asia/Karachi'

You might need to set USE_TZ as well.

USE_TZ = True
Metalgear
  • 3,391
  • 1
  • 7
  • 16