How to set time zone correct way?

:one: :wave:, i’ve set timezone in settings.py

:page_facing_up: settings.py

TIME_ZONE = 'Asia/Kolkata'

:two: models.py

from django.contrib.auth.models import AbstractUser
from django.db import models
from django.utils import timezone

class User(AbstractUser):
   [...]

class Post(models.Model):
    poster = models.ForeignKey(User, on_delete=models.CASCADE)
    content = models.TextField(max_length=500)
    timestamp = models.DateTimeField(default=timezone.now)

:three: in python shell

>>> post = Post.objects.create(poster=user,content='c1')
>>> post.save()
>>> Post.objects.all()
<QuerySet [<Post: (id: 1) poster: ganesh, content: c1, timestamp: 2020-12-01 02:35:41.861310+00:00>]>

:four: for timestamp field date is ok. but, the time django saves is not related to my timezone.

See the USE_TZ setting.

Also see Naive and aware datetime objects.

1 Like