Python中获取本机 时区/UTC偏移量 的几种方法

本文介绍了使用Python计算本地时间与UTC时间偏移量的五种方法,包括利用time模块、datetime模块及tzlocal库获取时区偏移,适用于不同场景下的时间同步需求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

通过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()

执行结果如下:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值