如何自动获取本地时区的时区抵消? [英] How do I automatically get the timezone offset for my local time zone?
问题描述
我正在尝试自动获取本地时区偏移量,但遇到麻烦。我试过:
I am trying to automate getting the local timezone offset but am having trouble. I've tried:
print time.timezone/3600
这个(当前错误的)偏移量不会自动调整为夏令时和非夏令时。
This gets the (currently wrong) offset as it doesn't automatically adjust for Daylight Savings Time and non-DST.
我也试过:
now_utc = pytz.utc.localize(datetime.datetime.now())
now_mst = now_utc.astimezone(pytz.timezone('US/Mountain'))
获得正确的偏移值,但我想自动设置US / Mountain部分,所以我不必手动输入任何东西来获得偏移量。
This gets the correct offset value, but I'd like to set 'US/Mountain' part automatically so I don't have to manually input anything to get the offset.
有没有办法获得正确的偏移量,可以使用DST&非DST?
Is there a way to get the correct offset that automatically adjusts with DST & non-DST?
我将在不同地理位置的多台服务器上运行此脚本,如果可以,我想自动获取tz偏移量。
I will be running this script on multiple servers in different geographies and I want to get the tz offset automatically if I can.
推荐答案
您可以使用 dateutil 模块。要立即获取当地时区:
You can use the dateutil module for this. To get the local timezone right now:
>>> import dateutil.tz
>>> import datetime
>>> localtz = dateutil.tz.tzlocal()
>>> localtz.tzname(datetime.datetime.now(localtz))
'EDT'
I目前在东部夏令时间。在夏令时切换回来之后,您可以看到它将会改回美国东部标准局。
I am currently in Eastern Daylight Time. You can see it change back to EST in the future, after daylight savings switches back:
>>> localtz.tzname(datetime.datetime.now(localtz) +
datetime.timedelta(weeks=20))
'EST'
如果您想要UTC的偏移量,可以使用utcoffset函数。它返回一个timedelta:
If you want the offset from UTC, you can use the utcoffset function. It returns a timedelta:
>>> localtz.utcoffset(datetime.datetime.now(localtz))
datetime.timedelta(-1, 72000)
在这种情况下,由于我是UTC-4,它返回-1天+ 20小时。您可以将其转换为数小时,如果您需要的话:
In this case, since I'm UTC-4, it returns -1 days + 20 hours. You can convert it to hours if that's what you need:
>>> localoffset = localtz.utcoffset(datetime.datetime.now(localtz))
>>> localoffset.total_seconds() / 3600
-4.0
这篇关于如何自动获取本地时区的时区抵消?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!