def tzinfo(self):
if self.df.empty:
return None
return self.df.index.levels[self.__class__.dtlevel].tzinfo
python类tzinfo()的实例源码
def tzinfo(self, tzinfo):
self.tz_convert(tzinfo)
def tz(self, tzinfo):
self.tz_convert(tzinfo)
def TimeEnd(self, timeend):
if timeend is None:
self._timeend = datetime.now(tz=pytz.utc)
elif not isinstance(timeend, datetime):
raise TypeError("req.TimeEnd must be a datetime.datetime object.")
else:
# Always use timezone-aware datetime.
if timeend.tzinfo is None:
_logger.warning('Naive HistDataReq.TimeEnd. '
'Assumeing system local time zone.')
tz_system = get_localzone()
timeend = tz_system.localize(timeend)
self._timeend = timeend
def hist_data_req_start_end(req: HistDataReq, xchg_tz: pytz.tzinfo):
"""
Calculate start and end datetime for a historical data request.
If req.TimeDur and BarSize both are in h/m/s, data range is limited to
the intraday data of req.TimeEnd.date().
:param xchg_tz: Time zone info of the security exchange for req.
"""
time_dur = req.TimeDur
end_dt = xchg_tz.normalize(req.TimeEnd)
if time_dur[-1] in ('W', 'M', 'Y'):
start_dt = xchg_tz.normalize(end_dt - timedur_to_reldelta(time_dur))
trd_days = trading_days(end_dt, time_start=start_dt)
elif time_dur[-1] is 'd':
# trd_days is a DateTimeIndex, with consecutive integer index.
trd_days = trading_days(end_dt, time_dur)
_logger.debug('trd_days: \n%s', trd_days)
start_date = trd_days.iloc[0].to_pydatetime()
start_dt = tzcomb(start_date, end_dt.time(), xchg_tz)
else: # TimeDur in h/m/s.
trd_days = trading_days(end_dt, time_dur)
_logger.debug('trd_days: \n%s', trd_days)
if req.BarSize[-1] is 'd':
# BarSize in d. Start time set to 00:00:00 of start date.
start_date = trd_days.iloc[0].to_pydatetime()
start_dt = tzmin(start_date, tz=xchg_tz)
else:
# BarSize in h/m/s; Limit to intraday data.
_logger.warning(
'req.TimeDur and req.BarSize are both in h/m/s.'
'Time range limit to intraday.')
start_date = trd_days.iloc[-1].to_pydatetime()
start_dt = max(tzmin(start_date, tz=xchg_tz),
xchg_tz.normalize(
end_dt-timedur_to_reldelta(req.TimeDur)))
return start_dt, end_dt, trd_days
def fromutc(self, dt):
if dt.tzinfo is None:
return self.localize(dt)
return super(utc.__class__, self).fromutc(dt)
def localize(self, dt, is_dst=False):
'''Convert naive time to local time'''
if dt.tzinfo is not None:
raise ValueError('Not naive datetime (tzinfo is already set)')
return dt.replace(tzinfo=self)
def normalize(self, dt, is_dst=False):
'''Correct the timezone information on the given datetime'''
if dt.tzinfo is self:
return dt
if dt.tzinfo is None:
raise ValueError('Naive time - no tzinfo set')
return dt.astimezone(self)
def _UTC():
"""Factory function for utc unpickling.
Makes sure that unpickling a utc instance always returns the same
module global.
These examples belong in the UTC class above, but it is obscured; or in
the README.txt, but we are not depending on Python 2.4 so integrating
the README.txt examples with the unit tests is not trivial.
>>> import datetime, pickle
>>> dt = datetime.datetime(2005, 3, 1, 14, 13, 21, tzinfo=utc)
>>> naive = dt.replace(tzinfo=None)
>>> p = pickle.dumps(dt, 1)
>>> naive_p = pickle.dumps(naive, 1)
>>> len(p) - len(naive_p)
17
>>> new = pickle.loads(p)
>>> new == dt
True
>>> new is dt
False
>>> new.tzinfo is dt.tzinfo
True
>>> utc is UTC is timezone('UTC')
True
>>> utc is timezone('GMT')
False
"""
return utc
def localize(self, dt, is_dst=False):
'''Convert naive time to local time'''
if dt.tzinfo is not None:
raise ValueError('Not naive datetime (tzinfo is already set)')
return dt.replace(tzinfo=self)
def normalize(self, dt, is_dst=False):
'''Correct the timezone information on the given datetime'''
if dt.tzinfo is None:
raise ValueError('Naive time - no tzinfo set')
return dt.replace(tzinfo=self)
def fromutc(self, dt):
if dt.tzinfo is None:
return self.localize(dt)
return super(utc.__class__, self).fromutc(dt)
def localize(self, dt, is_dst=False):
'''Convert naive time to local time'''
if dt.tzinfo is not None:
raise ValueError('Not naive datetime (tzinfo is already set)')
return dt.replace(tzinfo=self)
def normalize(self, dt, is_dst=False):
'''Correct the timezone information on the given datetime'''
if dt.tzinfo is self:
return dt
if dt.tzinfo is None:
raise ValueError('Naive time - no tzinfo set')
return dt.astimezone(self)
def _UTC():
"""Factory function for utc unpickling.
Makes sure that unpickling a utc instance always returns the same
module global.
These examples belong in the UTC class above, but it is obscured; or in
the README.txt, but we are not depending on Python 2.4 so integrating
the README.txt examples with the unit tests is not trivial.
>>> import datetime, pickle
>>> dt = datetime.datetime(2005, 3, 1, 14, 13, 21, tzinfo=utc)
>>> naive = dt.replace(tzinfo=None)
>>> p = pickle.dumps(dt, 1)
>>> naive_p = pickle.dumps(naive, 1)
>>> len(p) - len(naive_p)
17
>>> new = pickle.loads(p)
>>> new == dt
True
>>> new is dt
False
>>> new.tzinfo is dt.tzinfo
True
>>> utc is UTC is timezone('UTC')
True
>>> utc is timezone('GMT')
False
"""
return utc
def localize(self, dt, is_dst=False):
'''Convert naive time to local time'''
if dt.tzinfo is not None:
raise ValueError('Not naive datetime (tzinfo is already set)')
return dt.replace(tzinfo=self)
def normalize(self, dt, is_dst=False):
'''Correct the timezone information on the given datetime'''
if dt.tzinfo is None:
raise ValueError('Naive time - no tzinfo set')
return dt.replace(tzinfo=self)
def testGMT(self):
now = datetime.now(tz=GMT)
self.assertTrue(now.utcoffset() == NOTIME)
self.assertTrue(now.dst() == NOTIME)
self.assertTrue(now.timetuple() == now.utctimetuple())
self.assertTrue(now==now.replace(tzinfo=UTC))
def testUnknownOffsets(self):
# This tzinfo behavior is required to make
# datetime.time.{utcoffset, dst, tzname} work as documented.
dst_tz = pytz.timezone('US/Eastern')
# This information is not known when we don't have a date,
# so return None per API.
self.assertTrue(dst_tz.utcoffset(None) is None)
self.assertTrue(dst_tz.dst(None) is None)
# We don't know the abbreviation, but this is still a valid
# tzname per the Python documentation.
self.assertEqual(dst_tz.tzname(None), 'US/Eastern')
def _roundtrip_datetime(self, dt):
# Ensure that the tzinfo attached to a datetime instance
# is identical to the one returned. This is important for
# DST timezones, as some state is stored in the tzinfo.
tz = dt.tzinfo
p = pickle.dumps(dt)
unpickled_dt = pickle.loads(p)
unpickled_tz = unpickled_dt.tzinfo
self.assertTrue(tz is unpickled_tz, '%s did not roundtrip' % tz.zone)