django中aware和navie time的用法

今天想实现这样一个需求,记录用户创建某条数据距离现在的时间

通过下述代码创建一个tag模型:

class Tag(models.Model):
    tagname = models.CharField(max_length=20,null=False)
    create_time = models.DateTimeField(auto_now_add=True,null=True)
    class Meta:
        db_table = 'tag'

自定义一个过滤器用来实现该功能:

from datetime import datetime
from django import template
register = template.Library()
def timer(value):
    now_time = datetime.now()
    dis_time = now_time-value
    total_time = dis_time.total_seconds()
    if total_time < 60:
        return "%d秒以前"%total_time
    if total_time > 60 and total_time<60*60:
        total_time = int(total_time/(60))
        return "%d分钟以前"%total_time
    if total_time > 60*60 and total_time <60*60*24:
        total_time = int(total_time/(60*60))
        return "%d小时以前"%total_time
    if total_time > 60*60*24:
        total_time =  int(total_time/(60*60*24))
        return "%d天以前"%total_time
register.filter("timer",timer)

报错如下:

这是由于aware time和naive time所造成的

我们采用的解决办法有两个:

1、将模型 的aware time转换为naive time

2、将过滤器中的naive time转化为aware time

笔者首先采用方法一,事实证明不可行,报错为model不可以被调用

然后采用方法二:

通过如下代码将naive time转化为aware time

from django.utils.timezone import now
from pytz import timezone
from datetime import datetime
from django import template
register = template.Library()
def timer(value):
    now_time = datetime.now()
    now_time_1 = now_time.replace(tzinfo=timezone('UTC'))
    dis_time = now_time_1-value
    total_time = dis_time.total_seconds()
    if total_time < 60:
        return "%d秒以前"%total_time
    if total_time > 60 and total_time<60*60:
        total_time = int(total_time/(60))
        return "%d分钟以前"%total_time
    if total_time > 60*60 and total_time <60*60*24:
        total_time = int(total_time/(60*60))
        return "%d小时以前"%total_time
    if total_time > 60*60*24:
        total_time =  int(total_time/(60*60*24))
        return "%d天以前"%total_time
register.filter("timer",timer)

效果如下:

结果发现时间与真实的时间相差八个小时,这是由于我们采用的UTC时区所造成的,当然仍然是不可行的,

后来的解决办法如下:

from django.utils.timezone import now
from django import template
register = template.Library()
def timer(value):
    now_time = now()
    dis_time = now_time-value
    total_time = dis_time.total_seconds()
    if total_time < 60:
        return "%d秒以前"%total_time
    if total_time > 60 and total_time<60*60:
        total_time = int(total_time/(60))
        return "%d分钟以前"%total_time
    if total_time > 60*60 and total_time <60*60*24:
        total_time = int(total_time/(60*60))
        return "%d小时以前"%total_time
    if total_time > 60*60*24:
        total_time =  int(total_time/(60*60*24))
        return "%d天以前"%total_time
register.filter("timer",timer)

可以发现实现了该功能

总结:1、在django中支持时区,这是一个好消息也是一个坏消息

好处是我们可以进行国际化操作

坏处是如果我们不需要国际化,就会造成时间误差

2、

from django.utils.timezone import now

通过引入这个包的now方法,这个时间是带时区的,与模型中的时间保持一致

from datetime import datetime

引入这个包中的时间是不带时区的,因此会产生八个小时的时差

posted @ 2020-02-17 19:44  gaoshiguo112  阅读(226)  评论(0编辑  收藏  举报