Django:DateTimeField仅采用UTC格式,而非其他格式 [英] Django: DateTimeField taking UTC format only, not others
问题描述
要插入数据库的时间是默认的UTC,而不是基于时区的时间。我不明白为什么会这样,即使我在查询中特别指定了要插入的时间
The time that is being inserted in database is default UTC, not the timezone based time..I do not understand why is this happening, even though I am particularly specifying, in the query, the time that I want to be inserted.
在我的模型中,我有
class leave(models.Model):
date_created = models.DateTimeField(auto_now_add=True)
在我的设置中已
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
在我看来,我是根据员工所在国家/地区设置时区
In my views i am setting timezone based on employee country
if employees.objects.get(emp_id=request.user.username).emp_loc == 'IND':
tzone=pytz.timezone('Asia/Calcutta')
elif employees.objects.get(emp_id=request.user.username).emp_loc == 'MLA':
tzone=pytz.timezone('Asia/Manila')
elif employees.objects.get(emp_id=request.user.username).emp_loc == 'MPLS':
tzone=pytz.timezone('CST6CDT')
然后我根据以下信息创建休假并更新时区国家
And then I am creating leave and updating timezone based on country
new_leave = leave.objects.create(employee=employees.objects.get(emp_id = userid.emp_id), start_date=sdt, end_date=edt, ltype=ltyp, message=des,date_created=datetime.now(tzone))
new_leave.save()
谢谢。
推荐答案
您可以创建一个中间件来处理日期和时间,从django.utils中导入
pytz
You can create a middleware that handles the conversion of date and time, import pytz
from django.utils import timezone
from django.utils.deprecation import MiddlewareMixin
class TimezoneMiddleware(MiddlewareMixin):
def process_request(self, request):
tzname = request.session.get('django_timezone')
if tzname:
timezone.activate(pytz.timezone(tzname))
else:
timezone.deactivate()
一个d然后,您可以使用前面指定的条件轻松创建视图。
最好,如果您按照Kevin的建议阅读文档。
and then you can as easily create the view with the conditions that you indicated earlier. Best if you read the documentation as Kevin suggested.
这篇关于Django:DateTimeField仅采用UTC格式,而非其他格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!