阅读了很多文档之后,我对UTC,UTC时区以及如何在Django中使用它感到困惑。
UTC格式和UTC时区是一样的吗? UTC格式可以存储太平洋时区日期+时间吗?
我有一个带数据库和UI的django项目。
class FunModel(models.Model):
fun_time = models.DateTimeField()
我期待的是:
1)页面1.单击太平洋时区浏览器中的按钮。服务器创建/存储(在服务器端,而不是客户端创建时间)'fun_time'作为太平洋时区日期+时间(不是UTC区域,但格式是UTC格式)
2)第2页。加载第2页时。它将时间检索为太平洋日期+时间(不是UTC区域)
3)在数据库中,我希望看到存储的时间是太平洋日期+时间。
4)据我所知,FunModel类将以UTC格式存储太平洋时间。时区在设置中配置。
----Settings.py
# Tried 'US/Pacific' as well. No difference. Date+time stored in db is the same. Really confused!
TIME_ZONE = 'UTC'
# Only for retrieving date from db to be Pacific by calling active(USER_TIME_ZONE)?
USER_TIME_ZONE = 'US/Pacific'
# With above 2 settings, date stored/retrieved will be Pacific zone automatically. Not really!
USE_I18N = True
USE_L10N = True
USE_TZ = True
我的期望是数据库将时间存储为美国/太平洋时区,时间格式为UTC(总是UTC格式对吗?)
----Page1_Save.py
from django.utils import timezone
timezone.activate(settings.USER_TIME_ZONE)
time_param = timezone.localtime(timezone.now())
fun_time_obj = FunModel(fun_time=time_param)
fun_time_obj.save()
# time_param = 2019-04-16 01:00:00
# database: 2019-04-16 01:00:00 + 7 hours = 2019-04-16 08:00:00 (Not correct!)
我期待数据库:2019-04-16 01:00:00。
我也试过了,
time_param = timezone.now()
相同的结果:
# time_param = 2019-04-16 01:00:00
# database: 2019-04-16 01:00:00 + 7 hours = 2019-04-16 08:00:00 (Not correct!)
我哪里做错了?
---Page2_Load.py (Use Q to compare date stored in db)
# Browser in Pacific timezone without timezone passed to server. Just time picked from Javascript.
ui_date = '2019-04-16 01:00:00'
我想用Q函数来比较:
Q(fun_time__exact=ui_date)
A)如果数据库时间是太平洋时间,则比较有效。
B)如果数据库时间是UTC时间,则比较无效。现在,我无法比较db中存储的日期!怎么解决?
C)我不希望数据库中的日期+时间为UTC时区!
我得到了它的工作,但我对Django时区设置更加困惑。
服务器计算机系统时钟是UTC时区。
---settings.朋友
# Totally useless
#TIME_ZONE = 'UTC' # comment out, and server runs well.
# I suspect this is useless as well.
USER_TIME_ZONE = 'US/Pacific'
USE_I18N = True
USE_L10N = True
USE_TZ = False # Make server timezone not aware.
---怕个1_save.朋友
from datetime import datetime
import pytz
utc = pytz.utc.localize(datetime.utcnow()) # Generate time from server, which is UTC timezone
instance_time_zone = pytz.timezone('US/Pacific')
time_param = utc.astimezone(instance_time_zone)
time_param = time_param.replace(tzinfo=None) # USE_TZ = False. Make it without timezone.
fun_time_obj = FunModel(fun_time=time_param)
fun_time_obj.save()
现在,db中的时间是太平洋时间,这是我所期望的。
当USE_TZ = False时,TIME_ZONE,USER_TIME_ZONE在这种情况下无用。此外,USE_TZ = True,TIME_ZONE ='什么'似乎也没用,因为我尝试了TIME_ZONE ='US / Pacific',USER_TIME_ZONE ='US / Pacific',并且无法获得db来存储太平洋时间。