英文:
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.)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论