How to write the right time to DB according my timezone?

后端 未结 2 1027
野趣味
野趣味 2021-01-27 05:35

When I save dates in my database Django shows message about succesfull adding with the right time but in fact in the databese time is different

models.py:

2条回答
  •  执笔经年
    2021-01-27 06:05

    If i'm not mistaken, you must be in Russia which is 7 hours ahead of UTC. So, the server that you use must be using the UTC time which in my opinion is a good thing.
    I personally prefer to save times in UTC time in the data base and then convert them to the local time in the front end.

    from django.utils import timezone
    from datetime import datetime
    
    teg1 = Teg1(created_at=datetime.now(tz=timezone.utc)
    teg1.save()
    

    However, if you want to save the datetime in your local time, you can use:

    from datetime import datetime    
    import pytz
    
    novosibirsk = pytz.timezone("Asia/Novosibirsk")
    now = datetime.now(novosibirsk)
    teg1 = Teg1(created_at=now)
    teg1.save()
    

    Have in mind that in your admin interface, you might see the time and date based on the timezone you select in your settings.py. However, the data saved in the database is still in UTC time.

提交回复
热议问题