12

In one of my model I am storing time_stamp = models.DateTimeField(default=timezone.now)

But when I save the model it says You are 5.5 hours ahead of server time. for example local time in my machine is 13:02 but after saving what gets stored in db is 7:16

I got one related here but it does not an have a satisfying answer...

models.py

class Comment(models.Model):
    time_stamp = models.DateTimeField(default=timezone.now)

    def save(self, *args, **kwargs):
        ''' On save, update timestamps '''
        if not self.id:
            self.time_stamp = timezone.now()
        return super(Comment, self).save(*args, **kwargs)
Jayesh Singh
  • 696
  • 1
  • 9
  • 21

4 Answers4

23

As you are 5.5 hrs ahead of server time, I am assuming, you are in India.
So put appriopriate timezone in settings.py

TIME_ZONE = 'Asia/Kolkata'

If somewhere else, set accordingly

coderDude
  • 854
  • 8
  • 15
  • What if someone else uses the app? And that user is from a different timezone? – 0x5961736972 Feb 27 '21 at 09:55
  • IMO, in such situations you should store time in UTC i.e timezone unaware objects, and while displaying it to users, modify the time based on their local timezones. If you are using APIs, then its best to return the UTC UNIX timestamp and let the consumers of API decide what they want to do with it. If using web UI, In django templates, you can detect the timezones using `{% get_current_timezone as TIME_ZONE %}` @0x5961736972 Read this for more info https://docs.djangoproject.com/en/dev/topics/i18n/timezones/#get-current-timezone – coderDude Mar 03 '21 at 05:14
4

Make sure you make the following change in the settings.py file in your Django project.

Change in settings.py file

Sumit Banik
  • 304
  • 2
  • 7
3

If it is saying that you are 5.5 hours ahead of server time. It means that you are in India then set

TIME_ZONE = 'Asia/Kolkata' 

in your setting.py file.

Or check your time zone at https://en.wikipedia.org/wiki/List_of_tz_database_time_zones

gunj_desai
  • 782
  • 6
  • 19
-7

You need to change the time zone settings on your PC and refresh. That is the only way out. I just fixed my own through that.