Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django Rest Framework – datetime sent as str gets changed to different timezone when being saved to database?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading