在Django日期时间上使用strftime会在字符串中产生UTC时间 [英] Using strftime on a django datetime produces a UTC time in the string

查看:128
本文介绍了在Django日期时间上使用strftime会在字符串中产生UTC时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的一个模型中有以下代码:

I have the following code in one of my models:

def shortDescription(self):
    return self.name + ' ' + self.class_date.strftime("%I:%M")

self.class_date 是可识别时区的 DateTimeField self.class_date.is_aware() True USE_TZ True

self.class_date is a timezone aware DateTimeField, self.class_date.is_aware() is True, USE_TZ is True.

shortDescription返回一个以UTC而不是默认时区表示时间的字符串,并放置 {{aclass.class_date}} 显示正确区域中的时间。

The shortDescription returns a string that gives the time in UTC rather than the default timezone, putting {{ aclass.class_date }} in the template displays the time in the correct zone.

strftime 始终在基准上工作,本地时间?还是这里发生了什么?

Is strftime always working on the base, native time? Or what else is going on here?

推荐答案

当您直接引用日期时间段时,例如%I %M ,它直接使用它而不进行语言环境转换。如果包含%Z ,您会看到时间在 UTC 中。如果要获得可感知区域设置的结果,则需要使用更为有限的%X ,它只会吐出为该区域设置转换的全部时间。

When you directly reference pieces of the datetime like %I or %M, it uses it straight as it is with no locale conversion. If you included %Z you'd see that the time is in UTC. If you want locale-aware results, you need use the more limited %X, which will simply spit out the full time converted for the locale.

如果需要更多,则必须将其转换:

If you need more, you'll have to convert it:

from django.utils import timezone

def shortDescription(self):
    class_date = timezone.localtime(self.class_date)
    return self.name + ' ' + class_date.strftime("%I:%M")

或者,您可以依靠日期过滤器,它会自动为您执行此操作:

Or, you can rely on the date filter, which automatically does this for you:

from django.template import defaultfilters

def shortDescription(self):
    return self.name + ' ' + defaultfilters.date(self.class_date, 'g:i')

这篇关于在Django日期时间上使用strftime会在字符串中产生UTC时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆