2017-10-13 34 views
0

从数据库中,我查询了CREATED_DATE并把模板:如何将UTC时间转换为模板中的上海+8时区时间?

enter image description here

你看,这是UTC时间,我怎么能在模板显示+8时区的时间?

我尝试使用自定义模板过滤器来改变,但没有成功

from django import template 
from django.template.defaultfilters import stringfilter 
import datetime, time 

register = template.Library() 

### function 

def utc2local(utc_st): 
    """UTC时间转本地时间(+8:00)""" 
    now_stamp = time.time() 
    local_time = datetime.datetime.fromtimestamp(now_stamp) 
    utc_time = datetime.datetime.utcfromtimestamp(now_stamp) 
    offset = local_time - utc_time 
    local_st = utc_st + offset 

    return local_st 


@register.filter 
def convert_utc_to_shanghai(value): 
    """ 
    UTC->Shanghai 
    :param value: 
    :return: 
    """ 

    local_time = utc2local(value) 

    print local_time.strftime("% Y - % m - % d % H: % M: % S") 

    return local_time.strftime 
+0

请展示你的尝试。 – Sarcoma

+0

我的自定义过滤器似乎不起作用,我编辑了我的帖子。 – 244boy

+1

你试过django的['时区过滤器](https://docs.djangoproject.com/en/1.11/topics/i18n/timezones/#timezone)吗? – schwobaseggl

回答

0

我的解决方案是不保存UTC时间分贝,settings.py中设置此:

# Chinese Shanghai 
LANGUAGE_CODE = 'zh-hans' 
TIME_ZONE = 'Asia/Shanghai' 
# db does not use utc time 
USE_TZ = False 
相关问题