import time

print -time.timezone

它以秒为单位打印UTC偏移量(要考虑夏令时(DST),请参见time.altzone:is_dst = time.daylight and time.localtime().tm_isdst > 0

utc_offset = - (time.altzone if is_dst else time.timezone)

其中,utc offset是通过以下方式定义的:“若要获取本地时间,请将utc offset添加到utc time。”

在Python 3.3+中,如果底层C库支持它,则有^{} attribute:utc_offset = time.localtime().tm_gmtoff

注意:time.daylight可能在some edge cases中给出错误的结果。

tm_gmtoff由datetime自动使用,如果它在Python 3.3+上可用:from datetime import datetime, timedelta, timezone

d = datetime.now(timezone.utc).astimezone()

utc_offset = d.utcoffset() // timedelta(seconds=1)

要以解决time.daylight问题并在tm_gmtoff不可用的情况下仍能工作的方式获取当前UTC偏移量,可以使用@jts's suggestion子结构本地时间和UTC时间:import time

from datetime import datetime

ts = time.time()

utc_offset = (datetime.fromtimestamp(ts) -

datetime.utcfromtimestamp(ts)).total_seconds()

要获取过去/未来日期的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()

它在DST转换期间工作,在过去/未来日期工作,即使当地时区在当时有不同的UTC偏移量,例如2010-2015年期间的欧洲/莫斯科时区。

Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐