[英]How do I get Python to notice a change in the system timezone while running?
If I change my computer's timezone while a Python program is running, that program continues to use the old timezone for calculations and conversions unless I restart the program. 如果在运行Python程序时更改计算机的时区,除非重新启动该程序,否则该程序将继续使用旧时区进行计算和转换。
This causes trouble in situations such as parsing the output of commands which use local time, such as net stats svr
in Windows. 这会在诸如解析使用本地时间的命令输出(例如Windows中的
net stats svr
类的情况下引起麻烦。 Converting such a parsed local time to a Unix timestamp with time.mktime(local_naive_datetime.timetuple())
returns an incorrect timestamp unless the program is restarted because it assumes the local time is in the old timezone. 使用
time.mktime(local_naive_datetime.timetuple())
将已解析的本地时间转换为Unix时间戳会返回不正确的时间戳,除非重新启动程序,因为它假定本地时间在旧时区中。
A simple example demonstrating this problem: call datetime.datetime.now()
, change the system timezone, and call the function again. 演示此问题的简单示例:调用
datetime.datetime.now()
,更改系统时区,然后再次调用该函数。 The second call returns the local time in the old timezone. 第二个调用返回旧时区中的本地时间。
Is there a function or other method I can use to tell Python to recheck the system timezone without restarting a long-running script? 是否可以使用某种函数或其他方法来告诉Python重新检查系统时区,而无需重新启动长时间运行的脚本?
I am running Python 2.7.3 on Windows 7. 我在Windows 7上运行Python 2.7.3。
Yes there is a function. 是的,有一个功能。 You can call
time.tzset()
and you can use time.tzname
to get the time zone information. 您可以调用
time.tzset()
,也可以使用time.tzname
获取时区信息。
Please take a look at http://docs.python.org/2/library/time.html#time.tzset 请查看http://docs.python.org/2/library/time.html#time.tzset
This code worked to detect the change. 此代码可以检测到更改。 Not exactly production quality though.
虽然不完全是生产质量。
import os
import time
print(time.ctime(time.time()))
inp = input('change time and press enter')
f = open('newtimezone','w')
f.close()
print(time.ctime(os.stat('newtimezone').st_mtime))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.