Input current datetime in local time by default in django model

2.7k views Asked by At

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?

4

There are 4 answers

0
user1544500 On

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)

1
Anshuman Bharadwaj On

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)
0
Phares On

You need to change.

USE_TZ = False

By so doing you will stop using UTC and TIME_ZONE = 'Asia/Kolkata' will take effect.

0
kornislaw On

A common pattern for it is the following:

created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True)