gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 20:39:00 25 4
gpt4 key购买 nike

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

最佳答案

time.timezone :

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 偏移量通过以下方式定义:“要获取本地时间,请将 utc 偏移量添加到 utc 时间。”

在 Python 3.3+ 中有 tm_gmtoff attribute如果底层 C 库支持它:

utc_offset = time.localtime().tm_gmtoff

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

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)

要以解决 time.daylight 问题的方法获取当前 UTC 偏移量,并且即使 tm_gmtoff 不可用也能正常工作,@jts's suggestion可以使用 substruct 本地和 UTC 时间:

import time
from datetime import datetime

ts = time.time()
utc_offset = (datetime.fromtimestamp(ts) -
datetime.utcfromtimestamp(ts)).total_seconds()

要获取过去/ future 日期的 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 转换期间有效,它适用于过去/ future 的日期,即使本地时区在当时有不同的 UTC 偏移量,例如 2010-2015 年期间的欧洲/莫斯科时区。

关于python - 在 Python 中获取计算机的 UTC 偏移量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3168096/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com