django 1.4 - 无法比较offset-naive和offset-aware数据时间 [英] django 1.4 - can't compare offset-naive and offset-aware datetimes
问题描述
我有一个日常任务对象,其中包含一天的任务应该完成:
class DailyTask(models.Model):
time = models.TimeField()
last_completed = models.DateTimeField()
name = models.CharField(max_length = 100)
description = models.CharField(max_length = 1000)
weekends = models.BooleanField()
def __unicode __(self):
return'%s'%(self.name)
class Meta:
db_table = u'dailytask'
ordering = ['name']
为了检查一个任务是否仍然需要在今天完成,我具有以下代码:
def getDueDailyTasks():
dueDailyTasks = []
now = datetime。 datetime.now()
try:
dailyTasks = DailyTask.objects.all()
except dailyTask.DoesNotE xist:
return none
在dailyTasks中的dailyTask:
timeDue = datetime.datetime(now.year,now.month,now.day,dailyTask.time.hour,dailyTask.time.minute ,dailyTask.time.second)
如果timeDue< now和timeDue> dailyTask.last_completed:
如果dailyTask.weekends == False and now.weekday()> 4:
pass
else:
dueDailyTasks.append({'id':dailyTask.id,
'due':timeDue,
'name':dailyTask.name,
'description' :dailyTask.description})
return dueDailyTasks
这在1.2以下工作正常,但在1.4以下我得到错误:
无法比较偏移 - 天真和偏移感知的数据时间
由于行
if timeDue< ; now和timeDue> dailyTask.last_completed
两个比较条款都会抛出此错误。
我尝试使timeDue时区知道通过添加pytz.UTC作为参数,但这仍然引起了相同的错误。
我已经阅读了一些关于时区的文档,但是我是否很困惑需要使timeDue时区知道,或者是否需要对我的数据库和现有数据进行根本的更改。
检查< a href =https://docs.djangoproject.com/en/dev/topics/i18n/timezones/ =noreferrer>详细信息。详细信息。
通常,使用 django.utils.timezone.now
来创建一个偏移感知的当前日期时间
>>>来自django.utils import timezone
>>>> timezone.now()
datetime.datetime(2012,5,18,13,0,49,803031,tzinfo =< UTC)
和 django.utils.timezone.make_aware
制作偏移感知日期时间
>>> timezone.make_aware(datetime.datetime.now(),timezone.get_default_timezone())
datetime.datetime(2012,5,18,21,5,53,266396,tzinfo =< DstTzInfo'亚洲/ CST + 8:00:00 STD>)
然后,您可以比较两个偏移感知数据集, o麻烦
此外,您可以通过剥离时区信息将offset-awared datetime转换为offset-naive datetime,然后可以与正常 datetime .datetime.now()
,在utc下。
>>> t = timezone.now()#offset-awared datetime
pre>
>>>> t.astimezone(timezone.utc).replace(tzinfo = None)
datetime.datetime(2012,5,18,13,11,30,705324)
USE_TZ
是True
'默认'实际上,默认情况下是False
,而是由django-admin生成的
将其设置为settings.py
文件。 py startprojectTrue
),那么如果您的数据库支持时区感知时间,与时间相关的模型字段的值将是时区感知。您可以通过在设置中设置USE_TZ = False
(或简单地删除USE_TZ = True
)来禁用它。I am in the process of migrating an application from django 1.2 To 1.4.
I have a daily task object which contains a time of day that task should be completed:
class DailyTask(models.Model): time = models.TimeField() last_completed = models.DateTimeField() name = models.CharField(max_length=100) description = models.CharField(max_length=1000) weekends = models.BooleanField() def __unicode__(self): return '%s' % (self.name) class Meta: db_table = u'dailytask' ordering = ['name']
In order to check if a task is still required to be completed today, I have the following code:
def getDueDailyTasks(): dueDailyTasks=[] now = datetime.datetime.now() try: dailyTasks = DailyTask.objects.all() except dailyTask.DoesNotExist: return None for dailyTask in dailyTasks: timeDue = datetime.datetime(now.year,now.month,now.day,dailyTask.time.hour,dailyTask.time.minute,dailyTask.time.second) if timeDue<now and timeDue>dailyTask.last_completed: if dailyTask.weekends==False and now.weekday()>4: pass else: dueDailyTasks.append({'id':dailyTask.id, 'due':timeDue, 'name': dailyTask.name, 'description':dailyTask.description}) return dueDailyTasks
This worked fine under 1.2, But under 1.4 I get the error:
can't compare offset-naive and offset-aware datetimes
due to the line
if timeDue<now and timeDue>dailyTask.last_completed
and both comparison clauses throw this error.
I have tried making timeDue timezone aware by adding pytz.UTC as an argument, but this still raises the same error.
I've read some of the docs on timezones but am confused as to whether I just need to make timeDue timezone aware, or whether I need to make a fundamental change to my db and existing data.
解决方案Check the thorough document for detail info.
Normally, use
django.utils.timezone.now
to make an offset-aware current datetime>>> from django.utils import timezone >>> timezone.now() datetime.datetime(2012, 5, 18, 13, 0, 49, 803031, tzinfo=<UTC>)
And
django.utils.timezone.make_aware
to make an offset-aware datetime>>> timezone.make_aware(datetime.datetime.now(), timezone.get_default_timezone()) datetime.datetime(2012, 5, 18, 21, 5, 53, 266396, tzinfo=<DstTzInfo 'Asia/Shanghai' CST+8:00:00 STD>)
You could then compare both offset-aware datetimes w/o trouble.
Furthermore, you could convert offset-awared datetime to offset-naive datetime by stripping off timezone info, then it could be compared w/ normal
datetime.datetime.now()
, under utc.>>> t = timezone.now() # offset-awared datetime >>> t.astimezone(timezone.utc).replace(tzinfo=None) datetime.datetime(2012, 5, 18, 13, 11, 30, 705324)
USE_TZ
isTrue
'by default' (actually it'sFalse
by default, but thesettings.py
file generated bydjango-admin.py startproject
set it toTrue
), then if your DB supports timezone-aware times, values of time-related model fields would be timezone-aware. you could disable it by settingUSE_TZ=False
(or simply removeUSE_TZ=True
) in settings.这篇关于django 1.4 - 无法比较offset-naive和offset-aware数据时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!