Home > Net >  Django Rest Framework - datetime sent as str gets changed to different timezone when being saved to
Django Rest Framework - datetime sent as str gets changed to different timezone when being saved to

Time:10-05

I sent the following:

{'ticker': 'XYZ', 'last_price': 394.05, 'last_date_time': '2022-10-04 15:57:18'}

When it was saved in DB:

ticker: XYZ
last_price: 394.05
last_date_time: 2022-10-04 11:57:18

I am not sure how or why this gets changed.

models.py

class StockPriceModel(models.Model):
    ticker = models.CharField(max_length=30, blank=False, db_index=True)
    last_price = models.FloatField(blank=True, null=True)
    last_date_time = models.DateTimeField(db_index=True)
    created_at = models.DateTimeField(auto_now_add=True)

The auto_now_add field is also showing incorrect time.

It doesn't correspond to my date time setup in settings as below:

LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Dubai'
USE_I18N = True
USE_L10N = True
USE_TZ = True

CodePudding user response:

Django stores datetime in UTC timezone. See this doc for details. Since you specified 'Asia/Dubai' as default timezone. Django considers received value as 'Asia/Dubai' time and converts it to UTC before saving. If you need to change this logic try to use default_timezone argument in serializer's DateTimeField field:

class MySerializer:
    last_date_time = DateTimeField(default_timezone=pytz.utc)
  • Related