Reputation: 21
I have created a model in Django in which I want to input creation time by default in local time. I have set the following in settings.py:
TIME_ZONE = 'Asia/Kolkata'
USE_TZ = True
I have tried the following:
import pytz
status_timezone = pytz.timezone('Etc/UTC')
class Status(models.Model):
status = models.IntegerField(default=0, blank=True)
active = models.IntegerField(default=1, blank=True)
creation_date = models.DateTimeField(default=status_timezone.localize(datetime.now()))
This always gives the same datetime for all entries (time of model initialization
class Status(models.Model):
status = models.IntegerField(default=0, blank=True)
active = models.IntegerField(default=1, blank=True)
creation_date = models.DateTimeField(default=datetime.now)
This gives datetime in UTC
How to input datetime in IST by default?
Upvotes: 2
Views: 2785
Reputation: 51
Simplest way to do this would be like
in 'settings/py':
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Kolkata' #'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
in 'models.py':
from django.utils import timezone
creation_date = models.DateTimeField(default = timezone.now, blank=False)
Upvotes: 0
Reputation: 1028
You need to change.
USE_TZ = False
By so doing you will stop using UTC
and TIME_ZONE = 'Asia/Kolkata'
will take effect.
Upvotes: 3
Reputation: 1
A common pattern for it is the following:
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
Upvotes: 0
Reputation: 2147
As explained in the Django docs the auto_now_add is populated with the default time zone. As described here this is populated according to TIME_ZONE
settings.
Hence - I think the answer to your question would be:
TIME_ZONE=Asia/Kolkota
creation_date = models.DateTimeField(auto_add_now=True)
Upvotes: 0