Can we have Django DateTimeField without timezone?

前端 未结 1 985
予麋鹿
予麋鹿 2021-01-04 12:52

I have searched for this, and could not find any notes or tutorials.

相关标签:
1条回答
  • 2021-01-04 13:19

    When you set USE_TZ = True(see USE_TZ for more info) in your settings, Django stores date and time information in UTC in the database otherwise it will store naive date time (date time without timezone).

    The default settings.py file created by django-admin startproject includes USE_TZ = True for convenience.

    So you have to set USE_TZ = False in your settings to avoid attaching timezone.

    NOTE: However you cannot detach timezone only for a particular field. By following my suggestion above, you detach timezone from the entire database, so my guess is that it's better to use a CharField to store date without timezone.

    You can try to override the default save handler and remove the timezone from DatetimeField before saving the item into the database, by defining a save method for your model:

    def save(self, *args, **kwargs):
        self.datetime_field = self.datetime_field.replace(tzinfo=None)
        super(MyModel, self).save(*args, **kwargs)
    
    0 讨论(0)
提交回复
热议问题