django converting old datetime field to new 1.4 datetime with time zone aware in SQLite

家住魔仙堡 提交于 2020-01-02 05:46:06

问题


I have a django 1.3 project and I'm in the process of adding text notifications that will run on a certain schedule. As such, I'm going to need the app to be timezone aware. It looks like django 1.4 handles this pretty well. THe problem is that I am using SQLite for db, and it doesn't store the timezone info, so I have to convert. I'm a django newbie. ANy suggestions on how to convert datetime fields in SQLlite to timezone-aware fields.

By the way, when I launch the manage.py shell after upgrading to django 1.4 and activating timezone support, I get the following message:

RuntimeWarning: SQLite received a naive datetime (2012-04-05 15:18:49.939725) while 
time zone support is active. RuntimeWarning)

Thanks!


回答1:


You don't convert datetime fields in SQlite to timezone-aware fields. Within SQlite the datetime is still going to be naive but converted to UTC. And the timezone aware datetimes ara available at the application level.

For example, when you query for a Model instance from SQlite, that has a datetime field, Django:

  1. Gets the naive datetime from SQLite, sets it to aware datetime with UTC timezone
  2. So then when you access the model_instance.datetime_field, it's already timezone aware and localized to UTC
  3. Then in templates for example, you can localize it to current timezone

EDIT: Corrected my initially wrong answer, about what you get on the model instance.

If currently the datetimes in your SQlite db are not UTC, you'll need to do a one-time migration to convert them all to UTC. (and by UTC I just mean naive UTC value. As SQlite - and also MySQL - do not have datetime fields that store timezone info)

I suggest you read the timezone related documentation very carefully and thoroughly: https://docs.djangoproject.com/en/1.4/topics/i18n/timezones/

It's very easy to get this wrong.

Yes you'll get RunTimeWarning for every instance where your code "gives" naive datetimes to Django for saving. You'll have to fix those gradually, make them timezone-aware.



来源:https://stackoverflow.com/questions/10034823/django-converting-old-datetime-field-to-new-1-4-datetime-with-time-zone-aware-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!