在Python中获取UTC偏移量

huangapple go评论82阅读模式
英文:

Get the UTC offset in Python

问题

我试图以整数形式获取本地时间的UTC偏移量,单位为秒。我可以通过以下方式实现:

from datetime import datetime

now = datetime.now()
timezone = now.astimezone().tzinfo
offset = timezone.utcoffset(now).seconds

肯定有更好的方法,但我还没有找到。有什么建议吗?

英文:

I am trying to get the UTC offset for the local time in seconds as an int. I can do this in a roundabout way:

from datetime import datetime

now = datetime.now()
timezone = now.astimezone().tzinfo
offset = timezone.utcoffset(now).seconds

There must be a better way, but I haven't been able to find it. Any suggestions?

答案1

得分: 2

time.timezone 给出了本地非夏令时时区的偏移量。

当夏令时时区处于活动状态时,time.daylight 非零,而 time.altzone 给出了本地夏令时时区的 UTC 偏移量。

为了考虑所有情况,您需要检查 time.daylight 并相应地选择偏移量:

import time

offset = time.altzone if time.daylight else time.timezone

有关 time 模块的文档包含更多信息。

英文:

time.timezone gives the offset of the local non-DST timezone.

When a DST timezone is active, time.daylight is non-zero, and time.altzone gives you the UTC offset of the local DST timezone.

To account for all cases, you'd need to check time.daylight and select the offset accordingly:

import time

offset = time.altzone if time.daylight else time.timezone

The docs for the time module contain more information.

答案2

得分: 1

我发现我可以将公式缩短为一条语句:

from datetime import datetime

offset = datetime.now().astimezone().utcoffset().seconds
英文:

I found that I can shorten the formula somewhat, so it can be a single statement:

from datetime import datetime

offset = datetime.now().astimezone().utcoffset().seconds

答案3

得分: 0

That prints 25200, because I am currently 7 hours behind GMT, and 8 hours is 25200 seconds.

(I'm in PDT.)

英文:
import time
print(time.timezone - time.daylight*3600)

That prints 25200, because I am currently 7 hours behind GMT, and 8 hours is 25200 seconds.

(I'm in PDT.)

huangapple
  • 本文由 发表于 2023年8月4日 04:13:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76831360.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定