在python中获取系统本地时区
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35057968/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get system local timezone in python
提问by ntg
Seems strange, but I cannot find an easy way to find the local timezone using Pandas/pytz in Python.
看起来很奇怪,但我找不到在 Python 中使用 Pandas/pytz 找到本地时区的简单方法。
I can do:
我可以:
>>> pd.Timestamp('now', tz='utc').isoformat()
Out[47]: '2016-01-28T09:36:35.604000+00:00'
>>> pd.Timestamp('now').isoformat()
Out[48]: '2016-01-28T10:36:41.830000'
>>> pd.Timestamp('now').tz_localize('utc') - pd.Timestamp('now', tz='utc')
Out[49]: Timedelta('0 days 01:00:00')
Which will give me the timezone, but this is probably not the best way to do it... Is there a command in pytz or pandas to get the system time zone? (preferably in python 2.7 )
哪个会给我时区,但这可能不是最好的方法......在pytz或pandas中有没有命令来获取系统时区?(最好在 python 2.7 中)
采纳答案by Selcuk
I don't think this is possible using pytz
or pandas
, but you can always install python-dateutilor tzlocal:
我认为使用pytz
or是不可能的pandas
,但您始终可以安装python-dateutil或tzlocal:
from dateutil.tz import tzlocal
datetime.now(tzlocal())
or
或者
from tzlocal import get_localzone
local_tz = get_localzone()
回答by Martin Evans
time.timezone
should work.
time.timezone
应该管用。
The offset of the local (non-DST) timezone, in seconds west of UTC (negative in most of Western Europe, positive in the US, zero in the UK).
本地(非 DST)时区的偏移量,以 UTC 以西的秒数为单位(西欧大部分地区为负,美国为正,英国为零)。
Dividing by 3600 will give you the offset in hours:
除以 3600 将为您提供以小时为单位的偏移量:
import time
print(time.timezone / 3600.0)
This does not require any additional Python libraries.
这不需要任何额外的 Python 库。
回答by jeremysprofile
While it doesn't use pytz/Pandas, the other answers don't either, so I figured I should post what I'm using on mac/linux:
虽然它不使用 pytz/Pandas,但其他答案也不使用,所以我想我应该发布我在 mac/linux 上使用的内容:
import subprocess
timezone = subprocess.check_output("date +%Z")
Benefits over the other answers: respects daylight savings time, doesn't require additional libraries to be installed.
优于其他答案的好处:尊重夏令时,不需要安装额外的库。