2017-10-13 132 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