如何在不使用pytz.timezone()
方法的情况下从localize()
函数中仅获取 UTCOFFSET 值?
例如:
pytz.timezone('Asia/Calcutta')
给出:
DstTzInfo 'Asia/Calcutta' LMT+5:53:00 STD
在这里,我想只获得 LMT + 5:53 作为价值。
答案 0 :(得分:0)
您遇到的问题并不像从pytz.timezone对象获取UTCOFFSET那么简单,因为答案取决于您何时讨论。
例如,如果我想立即知道中心时区(美国)的UTCOFFSET ,答案是GMT-6。但如果我们在夏令时,答案就是GMT-5。所以什么时候重要!
我使用这样的东西在标准时间内获取每个时区的tzinfo对象。从那里,我认为你可以获取你想要的tzinfo属性。
def getPytzInSTD(tname):
"""
This returns a pytz timezone object normalized to standard time for the zone requested.
If the zone does not follow DST or a future transition time cannot be found, it normalizes to NOW instead.
:param tname: Proper timezone name found in the tzdatabase. example: "US/Central"
"""
# This defaults to the STD time for the zone rather than current time which could be DST
tzone = pytz.timezone(tname)
NOW = datetime.now(tz=pytz.UTC)
std_date = NOW
hasdst = False
try:
#transitions are in UTC. They need to be converted to localtime once we find the correct STD transition.
for utcdate, info in zip(tzone._utc_transition_times, tzone._transition_info):
utcdate = utcdate.replace(tzinfo=pytz.UTC)
utcoffset, dstoffset, tzname = info
if dstoffset == ZERO:
std_date = utcdate
if utcdate > NOW:
hasdst = True
break
except AttributeError:
std_date = NOW
if not hasdst:
std_date = NOW
std_date = tzone.normalize(std_date)
return std_date.tzinfo