在Python中获取计算机的UTC偏移量

Pau*_*aul 47 python timezone utc

在Python中,如何找到计算机设置的UTC时间偏移量?

jfs*_*jfs 81

time.timezone:

import time

print -time.timezone
Run Code Online (Sandbox Code Playgroud)

它以秒为单位打印UTC偏移量(考虑夏令时(DST),请参阅time.altzone:

is_dst = time.daylight and time.localtime().tm_isdst > 0
utc_offset = - (time.altzone if is_dst else time.timezone)
Run Code Online (Sandbox Code Playgroud)

其中utc偏移量通过以下方式定义:"要获取本地时间,请将utc偏移量添加到utc时间."

在Python 3.3+中,如果底层C库支持它,则有tm_gmtoff属性:

utc_offset = time.localtime().tm_gmtoff
Run Code Online (Sandbox Code Playgroud)

注意:time.daylight某些边缘情况下可能会给出错误的结果.

tm_gmtoff 如果在Python 3.3+上可用,则由datetime自动使用:

from datetime import datetime, timedelta, timezone

d = datetime.now(timezone.utc).astimezone()
utc_offset = d.utcoffset() // timedelta(seconds=1)
Run Code Online (Sandbox Code Playgroud)

要以解决time.daylight问题的方式获取当前UTC偏移量并且即使tm_gmtoff不可用也能正常工作,可以使用@jts建议的子网划分本地和UTC时间:

import time
from datetime import datetime

ts = time.time()
utc_offset = (datetime.fromtimestamp(ts) -
              datetime.utcfromtimestamp(ts)).total_seconds()
Run Code Online (Sandbox Code Playgroud)

要获得过去/未来日期的UTC偏移量,pytz可以使用时区:

from datetime import datetime
from tzlocal import get_localzone # $ pip install tzlocal

tz = get_localzone() # local timezone 
d = datetime.now(tz) # or some other local date 
utc_offset = d.utcoffset().total_seconds()
Run Code Online (Sandbox Code Playgroud)

它在DST过渡期间有效,即使当地时区在当时具有不同的UTC偏移量,例如2010-2015期间的欧洲/莫斯科时区,它也适用于过去/未来日期.

  • 这很好很干净。 (3认同)

小智 29

gmtime()将返回UTC时间并localtime()返回当地时间,因此减去两者应该给你utc偏移量.

  • @JasonTyler:避免比赛:[`t = localtime(); timegm(t) - timegm(gmtime(mktime(t)))`](https://mail.python.org/pipermail/datetime-sig/2015-September/000955.html) (6认同)
  • rakslice,try calendar.timegm(time.gmtime()) - calendar.timegm(time.localtime())) (4认同)
  • 减去它们会给出`TypeError:不支持的操作数类型 - :'time.struct_time'和'time.struct_time'`.你到底是什么意思? (3认同)

dst*_*erg 6

我喜欢:

>>> strftime('%z')
'-0700'
Run Code Online (Sandbox Code Playgroud)

我首先尝试了 JTS 的答案,但它给了我错误的结果。我现在在-0700,但它说我在-0800。但我必须先进行一些转换才能得到可以减去的东西,所以也许答案不完整而不是错误。

  • Python 不支持 `'%z'` (它可能在某些系统上工作,您可能可以使用 `time.localtime().tm_gmtoff` 来代替,以数字形式而不是字符串形式获取 utc 偏移量)。(“%z”的结果)应该与@jts'的答案相同。如果您不这么认为,请包括您的代码。 (2认同)
  • @dstromberg我认为这是最好的方法)我喜欢它!我的解决方案是: `int(datetime.now().astimezone().strftime("%z")[0:3])` (2认同)

归档时间:

查看次数:

36607 次

最近记录:

6 年,8 月 前