在Django中获取系统时间及时区,绕过默认时区

3
只要使用普通的Python shell,datetime.datetime.now() 命令就可以正常获取系统本地(非UTC)时间。但是我正在开发一个Django项目,在 settings.py 中通过 TIME_ZONE = 'UTC' 更改了时区。我尝试了许多解决方案,包括 django.utils timezonetzlocal 模块,但都没有成功。它们返回的时间要么不正确,要么是UTC时间。所有这些解决方案都适用于在 settings.py 中将时区更改为本地时区。但我不能这样做,有没有办法绕过 settings.py 中默认的时区选项?或者有没有自动更新 settings.py 时区的方法?如果我删除 TIME_ZONE 行,我不知道为什么,它似乎会得到一个随机的时区。编辑 - 我知道可以使用 pytz 手动输入时区,但我不想这样做。我想获取本地系统时区,但不带Django对时区的调整。谢谢。
3个回答

1
Django似乎将其时区放在TZ环境变量中。尝试使用del os.environ['TZ'],然后使用tzlocal。

0

要获取另一个时区的时间,请使用以下代码:

# create another timezone instance
import pytz
new_york_tz = pytz.timezone("America/New_York")

# get the current date and time, with the timezone set in your settings.py
from django.utils import timezone
d = timezone.now()
print(d)

# get the date and time in your other timezone
d2 = new_york_tz.normalize(d)
print(d2)

请参见:https://docs.djangoproject.com/en/1.10/topics/i18n/timezones/#naive-and-aware-datetime-objects


我知道这是可以做到的,但我不想手动输入时区。应用程序应该能够从计算机中获取默认时区,以某种方式绕过Django的时区设置。 - FadedCoder
1
“_WITHOUT Django的时区调整_” - PMARINA
datetime.datetime.now(dateutil.tz.tzlocal()) 对你有效吗? - Udi
dateutil.tz.tzlocal() 只是返回 tzlocal() - FadedCoder
不行,因为它会被 Django 的干预覆盖。 - FadedCoder

-2
你可以使用Javascript从浏览器获取时区偏移量到UTC。以下是代码。
var d = new Date()
var n = d.getTimezoneOffset()
alert(n)

结果是分钟数。例如,在洛杉矶您将得到480。如果结果是负数,则时区应为“西”,相反,正数表示“东”。1个时区= 60分钟,因此,您可以计算出480/60 = 8。然后结果是洛杉矶在西8时区。然后您可以使用pytz获取本地时间。


2
但这取决于客户端。就我理解的问题而言,OP想要服务器的本地时间(时区)。 - BlackJack

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接