[英]How to get the original local machine time zone in a Django application?
In Django you have a TIME_ZONE setting, which, as I understand, somehow patches the standard date and time packages in runtime, making them think the application is working in the time zone specified.在 Django 中,您有一个TIME_ZONE设置,据我了解,它以某种方式在运行时修补标准日期和时间包,使他们认为应用程序在指定的时区工作。 As a result, generic Python methods for determining local time zone do not work (they just show the configured time zone).
因此,用于确定本地时区的通用 Python 方法不起作用(它们只显示配置的时区)。
I can evaluate the link of /etc/localtime
like in this answer or use another Linux-specific method but I am concerned about the portability issue, as some developers run the app on Windows.我可以像在这个答案中一样评估
/etc/localtime
的链接,或者使用另一种特定于 Linux 的方法,但我担心可移植性问题,因为一些开发人员在 Windows 上运行该应用程序。
Can I find out in a platform independent way what was the original time zone on the machine?我可以以独立于平台的方式找出机器上的原始时区吗?
As there were no answers, I will post a workaround here.由于没有答案,我将在此处发布解决方法。
Though we cannot recover the initial time zone (without affecting the current settings), we can obtain and save it before Django's initialization.虽然我们无法恢复初始时区(不影响当前设置),但我们可以在 Django 初始化之前获取并保存它。 For example:
例如:
manage.py
:manage.py
:cmd = sys.argv[1] if len(sys.argv) >= 2 else ""
if cmd == "runserver":
from tzlocal import get_localzone
os.environ['MACHINE_TIME_ZONE'] = get_localzone().tzname(None)
# ...
execute_from_command_line(sys.argv)
gunicorn.conf.py
or wsgi.py
.gunicorn.conf.py
或wsgi.py
。 The main thing is tu put it somewhere before loading Django libraries:from tzlocal import get_localzone
os.environ['MACHINE_TIME_ZONE'] = get_localzone().tzname(None)
Later you can access this environment variable to retrieve the value.稍后您可以访问此环境变量以检索该值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.