如何在Python中从时区名称获取UTC偏移量?
例如:我有Asia/Jerusalem
,我想得到+0200
由于夏令时(Daylight Saving Time)的影响,结果取决于一年中的时间:
import datetime, pytz
datetime.datetime.now(pytz.timezone('Asia/Jerusalem')).strftime('%z')
# returns '+0300' (because 'now' they have DST)
pytz.timezone('Asia/Jerusalem').localize(datetime.datetime(2011,1,1)).strftime('%z')
# returns '+0200' (because in January they didn't have DST)
pytz.timezone("Etc/GMT-5").localize(datetime.datetime(2011, 1, 1)).strftime("%z")
返回的是 "+0500",而不是 "-0500"。 - 404usernamenotfoundEtc/GMT+n
。还有负数的时区Etc/GMT-n
。我让它正常工作了,但没有使用pytz。 - 404usernamenotfound你尝试过使用 pytz 项目和 utcoffset
方法吗?
例如:
>>> import datetime
>>> import pytz
>>> pacific_now = datetime.datetime.now(pytz.timezone('US/Pacific'))
>>> pacific_now.utcoffset().total_seconds()/60/60
-7.0
tzinfo
对象上使用。请参见 http://pytz.sourceforge.net/#tzinfo-api - Jon Skeettimezone.utcoffset()
的日期时间假定为该时区的本地时间,如果传递了夏令时开始或结束的小时,则会失败。更好的方法是使用datetime.datetime.utcnow().replace(tzinfo=pytz.utc).astimezone(pytz.timezone('US/Pacific')).utcoffset().total_seconds() / 60 / 60
。 - Nathan Villaescusa以下是@Jon Skeet 答案中的另一种观点,假设您已经有datetime.datetime
对象,例如day = datetime.datetime(2021, 4, 24)
:
import pytz
tz = pytz.timezone("Asia/Kolkata")
import datetime
day = datetime.datetime(2021, 4, 24)
offset = tz.utcoffset(day)/3600
在将python datetime对象转换为UTC时间戳时,我遇到了类似的问题。我的datetime对象没有时区(非常天真),因此astimezone
无法工作。
为了缓解这个问题,我让我的datetime对象有了时区意识,然后使用了上述方法。
import pytz
system_tz = pytz.timezone(constants.TIME_ZONE)
localized_time = system_tz.localize(time_of_meeting)
fmt = "%Y%m%dT%H%M%S" + 'Z'
return localized_time.astimezone(pytz.utc).strftime(fmt)
在这里,constants.TIME_ZONE
是我持久化对象的默认时区。
希望这能帮助那些试图将Python日期时间对象转换为UTC的人。一旦转换完成,可以按任意方式格式化。
以另一种方式将UTC偏移量转换为整数:
import datetime
import pytz
from tzwhere import tzwhere
tzwhere = tzwhere.tzwhere()
timezone = pytz.timezone('Asia/Jerusalem')
offSet_str = str(timezone.utcoffset(datetime.datetime.now()))
if offSet_str[0] != '-':
offSet = int(offSet_str[0])
else:
offSet = int(offSet_str[8] + offSet_str[9]) - 24
print(offSet)
Jon Skeet有一种更快的方法
datetime.datetime.now(zoneinfo.ZoneInfo('Asia/Jerusalem')).utcoffset()
,无需使用任何第三方库。 - FObersteiner