如何在模板中将UTC时间转换为上海+8时区时间?

时间:2017-10-13 06:09:00

标签: python django

从数据库中,我查询created_date并输入模板:

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

2 个答案:

答案 0 :(得分:1)

我的解决方案是不会将utc时间保存到db,请在settings.py中设置:

tuneGrid

答案 1 :(得分:0)

timezone.localtime

settings.py

LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
USE_TZ = True

$ ./manage.py shell

Python 3.6.5 (default, Apr  1 2018, 05:46:30)
Type 'copyright', 'credits' or 'license' for more information
IPython 6.4.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: from django.utils import timezone

In [2]: timezone.now()
Out[2]: datetime.datetime(2018, 7, 24, 12, 57, 8, 32455, tzinfo=<UTC>)

In [3]: timezone.localtime(timezone.now())
Out[3]: datetime.datetime(2018, 7, 24, 20, 57, 18, 743225, tzinfo=<DstTzInfo 'Asia/Shanghai' CST+8:00:00 STD>)

解决方案2: pytz

In [1]: import pytz

In [2]: from datetime import datetime

In [7]: datetime.utcnow().replace(tzinfo=pytz.utc).astimezone(pytz.timezone('Asia/Shanghai'))
Out[7]: datetime.datetime(2018, 7, 25, 11, 35, 58, 15629, tzinfo=<DstTzInfo 'Asia/Shanghai' CST+8:00:00 STD>)

In [8]: str(_)
Out[8]: '2018-07-25 11:35:58.015629+08:00'

解决方案3: maya https://github.com/kennethreitz/maya

In [1]: import maya

In [2]: maya.now().datetime('Asia/Shanghai')
Out[2]: datetime.datetime(2018, 7, 25, 17, 24, 15, 461077, tzinfo=<DstTzInfo 'Asia/Shanghai' CST+8:00:00 STD>)

In [3]: str(_)
Out[3]: '2018-07-25 17:24:15.461077+08:00'