通过Python获取时区的方法比较简单,利用tzlocal.get_localzone()就可以获取了
主要记录以下计算UTC偏移量的几种方法
import time
import tzlocal
import datetime
def _format_offset(seconds_offset):
"""
将偏移秒数转换为UTC±X
注意:这里没有考虑时区偏移非整小时的,使用请修改处理方式
:param seconds_offset 偏移秒数
:return: 格式化后的时区偏移
"""
hours_offset = int(seconds_offset/60/60)
if hours_offset >= 0:
return "UTC+" + str(hours_offset)
else:
return "UTC" + str(hours_offset)
def main():
# 方法一:
print(time.strftime('%z'))
# 方法二:
seconds_offset = time.localtime().tm_gmtoff
print(_format_offset(seconds_offset))
# 方法三:
is_dst = time.daylight and time.localtime().tm_isdst > 0
seconds_offset = - (time.altzone if is_dst else time.timezone)
print(_format_offset(seconds_offset))
# 方法四:
ts = time.time()
seconds_offset = (datetime.datetime.fromtimestamp(ts) - datetime.datetime.utcfromtimestamp(ts)).total_seconds()
print(_format_offset(seconds_offset))
# 方法五:
seconds_offset = int(datetime.datetime.now(tzlocal.get_localzone()).utcoffset().total_seconds())
print(_format_offset(seconds_offset))
if __name__ == "__main__":
main()
执行结果如下: