在Django中绕过默认时区获取带有时区的系统时间 [英] Get system time w/timezone in Django bypassing default timezone

查看:48
本文介绍了在Django中绕过默认时区获取带有时区的系统时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只要我使用的是普通的Python shell, datetime.datetime.now()命令就可以很好地获取系统的本地(非UTC)时间.

As long as I'm using plain ol' Python shell, the datetime.datetime.now() command works fine to get system's local (non-UTC) time.

但是我正在研究一个Django项目,其中时区在 settings.py 中通过 TIME_ZONE ='UTC'进行了更改.

But I'm working on a Django project where the time zone is changed in settings.py with TIME_ZONE = 'UTC'.

我已经尝试了从 django.utils时区 tzlocal 模块的许多解决方案,但是它们都不起作用.它们全部返回错误的时间或UTC时间.

I've tried many solutions from django.utils timezone to tzlocal module, but none of them works. All of them return either incorrect or UTC time.

如果我将 settings.py 中的时区更改为我的本地时区,则所有解决方案都可以使用.但是我不能这样做,所以有什么办法可以绕过 settings.py 中的默认时区选项?还是可以通过任何方式自动更新 settings.py 的时区?如果我删除 TIME_ZONE 行,我不知道为什么,但是它似乎得到了一个随机的时区.

All of the solutions work if I change the timezone in settings.py to my local timezone. But I can't do that, so is there any way to bypass the default timezone option in settings.py? Or any way the settings.py's timezone can be automatically updated? If I remove the TIME_ZONE line, I don't know why, but it seems to get a random timezone.

编辑-

我知道可以使用 pytz 手动输入时区,但是我不想这样做.我想获取本地系统的时区,但是没有Django的时区.

I know that the timezone can be entered manually with pytz, but I don't want to do that. I want to get the local system timezone, but WITHOUT Django's moderation of the timezone.

谢谢.

推荐答案

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

Django seems to be putting its timezone in the TZ environment variable. Try del os.environ['TZ'] then using tzlocal.

这篇关于在Django中绕过默认时区获取带有时区的系统时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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