Python pytz 模块,tzinfo() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用pytz.tzinfo()

项目:sndlatr    作者:Schibum    | 项目源码 | 文件源码
def test_arithmetic(self):
        utc_dt = self.transition_time

        for days in range(-420, 720, 20):
            delta = timedelta(days=days)

            # Make sure we can get back where we started
            dt = utc_dt.astimezone(self.tzinfo)
            dt2 = dt + delta
            dt2 = dt2 - delta
            self.assertEqual(dt, dt2)

            # Make sure arithmetic crossing DST boundaries ends
            # up in the correct timezone after normalization
            utc_plus_delta = (utc_dt + delta).astimezone(self.tzinfo)
            local_plus_delta = self.tzinfo.normalize(dt + delta)
            self.assertEqual(
                    prettydt(utc_plus_delta),
                    prettydt(local_plus_delta),
                    'Incorrect result for delta==%d days.  Wanted %r. Got %r'%(
                        days,
                        prettydt(utc_plus_delta),
                        prettydt(local_plus_delta),
                        )
                    )
项目:sndlatr    作者:Schibum    | 项目源码 | 文件源码
def testPartialMinuteOffsets(self):
        # utcoffset in Amsterdam was not a whole minute until 1937
        # However, we fudge this by rounding them, as the Python
        # datetime library 
        tz = pytz.timezone('Europe/Amsterdam')
        utc_dt = datetime(1914, 1, 1, 13, 40, 28, tzinfo=UTC) # correct
        utc_dt = utc_dt.replace(second=0) # But we need to fudge it
        loc_dt = utc_dt.astimezone(tz)
        self.assertEqual(
                loc_dt.strftime('%Y-%m-%d %H:%M:%S %Z%z'),
                '1914-01-01 14:00:00 AMT+0020'
                )

        # And get back...
        utc_dt = loc_dt.astimezone(UTC)
        self.assertEqual(
                utc_dt.strftime('%Y-%m-%d %H:%M:%S %Z%z'),
                '1914-01-01 13:40:00 UTC+0000'
                )
项目:ibstract    作者:jesseliu0    | 项目源码 | 文件源码
def query_hist_data(
        engine: object, sectype: str, symbol: str, datatype: str, barsize: str,
        start: datetime=None, end: datetime=None) -> MarketDataBlock:
    """Query database on conditions.
    """
    if start is None:
        start = pytz.UTC.localize(datetime(1, 1, 1))
    if end is None:
        end = pytz.UTC.localize(datetime(9999, 12, 31, 23, 59, 59))
    table = _gen_sa_table(sectype)
    stmt = table.select().where(
        and_(
            table.c.Symbol == symbol,
            table.c.DataType == datatype,
            table.c.BarSize == barsize,
            table.c.TickerTime.between(
                start.astimezone(pytz.UTC), end.astimezone(pytz.UTC))
        )
    )
    async with engine.acquire() as conn:
        result = await conn.execute(stmt)
    df = pd.DataFrame(list(result), columns=table.columns.keys())
    blk = MarketDataBlock(df, tz='UTC')
    blk.tz_convert(start.tzinfo)
    return blk
项目:epg-dk.bundle    作者:ukdtom    | 项目源码 | 文件源码
def testOldPickles(self):
        # Ensure that applications serializing pytz instances as pickles
        # have no troubles upgrading to a new pytz release. These pickles
        # where created with pytz2006j
        east1 = pickle.loads(_byte_string(
            "cpytz\n_p\np1\n(S'US/Eastern'\np2\nI-18000\n"
            "I0\nS'EST'\np3\ntRp4\n."
            ))
        east2 = pytz.timezone('US/Eastern').localize(
            datetime(2006, 1, 1)).tzinfo
        self.assertTrue(east1 is east2)

        # Confirm changes in name munging between 2006j and 2007c cause
        # no problems.
        pap1 = pickle.loads(_byte_string(
            "cpytz\n_p\np1\n(S'America/Port_minus_au_minus_Prince'"
            "\np2\nI-17340\nI0\nS'PPMT'\np3\ntRp4\n."))
        pap2 = pytz.timezone('America/Port-au-Prince').localize(
            datetime(1910, 1, 1)).tzinfo
        self.assertTrue(pap1 is pap2)

        gmt1 = pickle.loads(_byte_string(
            "cpytz\n_p\np1\n(S'Etc/GMT_plus_10'\np2\ntRp3\n."))
        gmt2 = pytz.timezone('Etc/GMT+10')
        self.assertTrue(gmt1 is gmt2)
项目:epg-dk.bundle    作者:ukdtom    | 项目源码 | 文件源码
def test_arithmetic(self):
        utc_dt = self.transition_time

        for days in range(-420, 720, 20):
            delta = timedelta(days=days)

            # Make sure we can get back where we started
            dt = utc_dt.astimezone(self.tzinfo)
            dt2 = dt + delta
            dt2 = dt2 - delta
            self.assertEqual(dt, dt2)

            # Make sure arithmetic crossing DST boundaries ends
            # up in the correct timezone after normalization
            utc_plus_delta = (utc_dt + delta).astimezone(self.tzinfo)
            local_plus_delta = self.tzinfo.normalize(dt + delta)
            self.assertEqual(
                    prettydt(utc_plus_delta),
                    prettydt(local_plus_delta),
                    'Incorrect result for delta==%d days.  Wanted %r. Got %r'%(
                        days,
                        prettydt(utc_plus_delta),
                        prettydt(local_plus_delta),
                        )
                    )
项目:epg-dk.bundle    作者:ukdtom    | 项目源码 | 文件源码
def testPartialMinuteOffsets(self):
        # utcoffset in Amsterdam was not a whole minute until 1937
        # However, we fudge this by rounding them, as the Python
        # datetime library
        tz = pytz.timezone('Europe/Amsterdam')
        utc_dt = datetime(1914, 1, 1, 13, 40, 28, tzinfo=UTC) # correct
        utc_dt = utc_dt.replace(second=0) # But we need to fudge it
        loc_dt = utc_dt.astimezone(tz)
        self.assertEqual(
                loc_dt.strftime('%Y-%m-%d %H:%M:%S %Z%z'),
                '1914-01-01 14:00:00 AMT+0020'
                )

        # And get back...
        utc_dt = loc_dt.astimezone(UTC)
        self.assertEqual(
                utc_dt.strftime('%Y-%m-%d %H:%M:%S %Z%z'),
                '1914-01-01 13:40:00 UTC+0000'
                )
项目:epg-dk.bundle    作者:ukdtom    | 项目源码 | 文件源码
def test_fromutc(self):
        # naive datetime.
        dt1 = datetime(2011, 10, 31)

        # localized datetime, same timezone.
        dt2 = self.tz.localize(dt1)

        # Both should give the same results. Note that the standard
        # Python tzinfo.fromutc() only supports the second.
        for dt in [dt1, dt2]:
            loc_dt = self.tz.fromutc(dt)
            loc_dt2 = pytz.utc.localize(dt1).astimezone(self.tz)
            self.assertEqual(loc_dt, loc_dt2)

        # localized datetime, different timezone.
        new_tz = pytz.timezone('Europe/Paris')
        self.assertTrue(self.tz is not new_tz)
        dt3 = new_tz.localize(dt1)
        self.assertRaises(ValueError, self.tz.fromutc, dt3)
项目:isf    作者:w3h    | 项目源码 | 文件源码
def info(self, t=None):
        if t is None:
            dt = datetime.utcnow().replace(tzinfo=pytz.utc)
        else:
            # can't use utcfromtimestamp past 2038
            dt = EPOCH + timedelta(0, t)

        # need to normalize tzinfo for the datetime to deal with
        # daylight savings time.
        normalized_dt = self.tzinfo.normalize(dt.astimezone(self.tzinfo))
        normalized_tzinfo = normalized_dt.tzinfo

        offset = normalized_tzinfo.utcoffset(normalized_dt)
        secs = offset.days * 24 * 60 * 60 + offset.seconds
        dst = normalized_tzinfo.dst(normalized_dt)
        if dst == timedelta(0):
            is_dst = 0
        else:
            is_dst = 1
        return secs, is_dst, normalized_tzinfo.tzname(normalized_dt)
项目:start    作者:argeweb    | 项目源码 | 文件源码
def test_arithmetic(self):
        utc_dt = self.transition_time

        for days in range(-420, 720, 20):
            delta = timedelta(days=days)

            # Make sure we can get back where we started
            dt = utc_dt.astimezone(self.tzinfo)
            dt2 = dt + delta
            dt2 = dt2 - delta
            self.assertEqual(dt, dt2)

            # Make sure arithmetic crossing DST boundaries ends
            # up in the correct timezone after normalization
            utc_plus_delta = (utc_dt + delta).astimezone(self.tzinfo)
            local_plus_delta = self.tzinfo.normalize(dt + delta)
            self.assertEqual(
                    prettydt(utc_plus_delta),
                    prettydt(local_plus_delta),
                    'Incorrect result for delta==%d days.  Wanted %r. Got %r'%(
                        days,
                        prettydt(utc_plus_delta),
                        prettydt(local_plus_delta),
                        )
                    )
项目:start    作者:argeweb    | 项目源码 | 文件源码
def testPartialMinuteOffsets(self):
        # utcoffset in Amsterdam was not a whole minute until 1937
        # However, we fudge this by rounding them, as the Python
        # datetime library 
        tz = pytz.timezone('Europe/Amsterdam')
        utc_dt = datetime(1914, 1, 1, 13, 40, 28, tzinfo=UTC) # correct
        utc_dt = utc_dt.replace(second=0) # But we need to fudge it
        loc_dt = utc_dt.astimezone(tz)
        self.assertEqual(
                loc_dt.strftime('%Y-%m-%d %H:%M:%S %Z%z'),
                '1914-01-01 14:00:00 AMT+0020'
                )

        # And get back...
        utc_dt = loc_dt.astimezone(UTC)
        self.assertEqual(
                utc_dt.strftime('%Y-%m-%d %H:%M:%S %Z%z'),
                '1914-01-01 13:40:00 UTC+0000'
                )
项目:cloud-memory    作者:onejgordon    | 项目源码 | 文件源码
def test_arithmetic(self):
        utc_dt = self.transition_time

        for days in range(-420, 720, 20):
            delta = timedelta(days=days)

            # Make sure we can get back where we started
            dt = utc_dt.astimezone(self.tzinfo)
            dt2 = dt + delta
            dt2 = dt2 - delta
            self.assertEqual(dt, dt2)

            # Make sure arithmetic crossing DST boundaries ends
            # up in the correct timezone after normalization
            utc_plus_delta = (utc_dt + delta).astimezone(self.tzinfo)
            local_plus_delta = self.tzinfo.normalize(dt + delta)
            self.assertEqual(
                    prettydt(utc_plus_delta),
                    prettydt(local_plus_delta),
                    'Incorrect result for delta==%d days.  Wanted %r. Got %r'%(
                        days,
                        prettydt(utc_plus_delta),
                        prettydt(local_plus_delta),
                        )
                    )
项目:cloud-memory    作者:onejgordon    | 项目源码 | 文件源码
def testPartialMinuteOffsets(self):
        # utcoffset in Amsterdam was not a whole minute until 1937
        # However, we fudge this by rounding them, as the Python
        # datetime library 
        tz = pytz.timezone('Europe/Amsterdam')
        utc_dt = datetime(1914, 1, 1, 13, 40, 28, tzinfo=UTC) # correct
        utc_dt = utc_dt.replace(second=0) # But we need to fudge it
        loc_dt = utc_dt.astimezone(tz)
        self.assertEqual(
                loc_dt.strftime('%Y-%m-%d %H:%M:%S %Z%z'),
                '1914-01-01 14:00:00 AMT+0020'
                )

        # And get back...
        utc_dt = loc_dt.astimezone(UTC)
        self.assertEqual(
                utc_dt.strftime('%Y-%m-%d %H:%M:%S %Z%z'),
                '1914-01-01 13:40:00 UTC+0000'
                )
项目:sndlatr    作者:Schibum    | 项目源码 | 文件源码
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))
项目:sndlatr    作者:Schibum    | 项目源码 | 文件源码
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')
项目:sndlatr    作者:Schibum    | 项目源码 | 文件源码
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)
项目:sndlatr    作者:Schibum    | 项目源码 | 文件源码
def testDst(self):
        tz = pytz.timezone('Europe/Amsterdam')
        dt = datetime(2004, 2, 1, 0, 0, 0)

        for localized_tz in tz._tzinfos.values():
            self._roundtrip_tzinfo(localized_tz)
            self._roundtrip_datetime(dt.replace(tzinfo=localized_tz))
项目:sndlatr    作者:Schibum    | 项目源码 | 文件源码
def _test_tzname(self, utc_dt, wanted):
        tzname = wanted['tzname']
        dt = utc_dt.astimezone(self.tzinfo)
        self.assertEqual(dt.tzname(), tzname,
            'Expected %s as tzname for %s. Got %s' % (
                tzname, str(utc_dt), dt.tzname()
                )
            )
项目:sndlatr    作者:Schibum    | 项目源码 | 文件源码
def _test_dst(self, utc_dt, wanted):
        dst = wanted['dst']
        dt = utc_dt.astimezone(self.tzinfo)
        self.assertEqual(dt.dst(),dst,
            'Expected %s as dst for %s. Got %s' % (
                dst, utc_dt, dt.dst()
                )
            )
项目:sndlatr    作者:Schibum    | 项目源码 | 文件源码
def testNormalize(self):
        tz = pytz.timezone('US/Eastern')
        dt = datetime(2004, 4, 4, 7, 0, 0, tzinfo=UTC).astimezone(tz)
        dt2 = dt - timedelta(minutes=10)
        self.assertEqual(
                dt2.strftime('%Y-%m-%d %H:%M:%S %Z%z'),
                '2004-04-04 02:50:00 EDT-0400'
                )

        dt2 = tz.normalize(dt2)
        self.assertEqual(
                dt2.strftime('%Y-%m-%d %H:%M:%S %Z%z'),
                '2004-04-04 01:50:00 EST-0500'
                )
项目:sndlatr    作者:Schibum    | 项目源码 | 文件源码
def no_testCreateLocaltime(self):
        # It would be nice if this worked, but it doesn't.
        tz = pytz.timezone('Europe/Amsterdam')
        dt = datetime(2004, 10, 31, 2, 0, 0, tzinfo=tz)
        self.assertEqual(
                dt.strftime(fmt),
                '2004-10-31 02:00:00 CET+0100'
                )
项目:sndlatr    作者:Schibum    | 项目源码 | 文件源码
def test_normalize(self):
        other_tz = pytz.timezone('Europe/Paris')
        self.assertTrue(self.tz is not other_tz)

        dt = datetime(2012, 3, 26, 12, 0)
        other_dt = other_tz.localize(dt)

        local_dt = self.tz.normalize(other_dt)

        self.assertTrue(local_dt.tzinfo is not other_dt.tzinfo)
        self.assertNotEqual(
            local_dt.replace(tzinfo=None), other_dt.replace(tzinfo=None))
项目:sndlatr    作者:Schibum    | 项目源码 | 文件源码
def test_astimezone(self):
        other_tz = pytz.timezone('Europe/Paris')
        self.assertTrue(self.tz is not other_tz)

        dt = datetime(2012, 3, 26, 12, 0)
        other_dt = other_tz.localize(dt)

        local_dt = other_dt.astimezone(self.tz)

        self.assertTrue(local_dt.tzinfo is not other_dt.tzinfo)
        self.assertNotEqual(
            local_dt.replace(tzinfo=None), other_dt.replace(tzinfo=None))
项目:sndlatr    作者:Schibum    | 项目源码 | 文件源码
def test_suite():
    suite = unittest.TestSuite()
    suite.addTest(doctest.DocTestSuite('pytz'))
    suite.addTest(doctest.DocTestSuite('pytz.tzinfo'))
    import test_tzinfo
    suite.addTest(unittest.defaultTestLoader.loadTestsFromModule(test_tzinfo))
    return suite
项目:sndlatr    作者:Schibum    | 项目源码 | 文件源码
def fromutc(self, dt):
        if dt.tzinfo is None:
            return self.localize(dt)
        return super(utc.__class__, self).fromutc(dt)
项目:sndlatr    作者:Schibum    | 项目源码 | 文件源码
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)
项目:sndlatr    作者:Schibum    | 项目源码 | 文件源码
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
项目:sndlatr    作者:Schibum    | 项目源码 | 文件源码
def _p(*args):
    """Factory function for unpickling pytz tzinfo instances.

    Just a wrapper around tzinfo.unpickler to save a few bytes in each pickle
    by shortening the path.
    """
    return unpickler(*args)
项目:sndlatr    作者:Schibum    | 项目源码 | 文件源码
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)
项目:sndlatr    作者:Schibum    | 项目源码 | 文件源码
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)
项目:ibstract    作者:jesseliu0    | 项目源码 | 文件源码
def tz_convert(self, tzinfo):
        if not self.df.empty:
            self.df = self.df.tz_convert(tzinfo, level=self.__class__.dtlevel)
项目:ibstract    作者:jesseliu0    | 项目源码 | 文件源码
def tzinfo(self):
        if self.df.empty:
            return None
        return self.df.index.levels[self.__class__.dtlevel].tzinfo
项目:ibstract    作者:jesseliu0    | 项目源码 | 文件源码
def tzinfo(self, tzinfo):
        self.tz_convert(tzinfo)
项目:ibstract    作者:jesseliu0    | 项目源码 | 文件源码
def tz(self, tzinfo):
        self.tz_convert(tzinfo)
项目:ibstract    作者:jesseliu0    | 项目源码 | 文件源码
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
项目:ibstract    作者:jesseliu0    | 项目源码 | 文件源码
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
项目:Texty    作者:sarthfrey    | 项目源码 | 文件源码
def fromutc(self, dt):
        if dt.tzinfo is None:
            return self.localize(dt)
        return super(utc.__class__, self).fromutc(dt)
项目:Texty    作者:sarthfrey    | 项目源码 | 文件源码
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)
项目:Texty    作者:sarthfrey    | 项目源码 | 文件源码
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)
项目:Texty    作者:sarthfrey    | 项目源码 | 文件源码
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
项目:Texty    作者:sarthfrey    | 项目源码 | 文件源码
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)
项目:Texty    作者:sarthfrey    | 项目源码 | 文件源码
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)
项目:aws-ops-automator    作者:awslabs    | 项目源码 | 文件源码
def fromutc(self, dt):
        if dt.tzinfo is None:
            return self.localize(dt)
        return super(utc.__class__, self).fromutc(dt)
项目:aws-ops-automator    作者:awslabs    | 项目源码 | 文件源码
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)
项目:aws-ops-automator    作者:awslabs    | 项目源码 | 文件源码
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)
项目:aws-ops-automator    作者:awslabs    | 项目源码 | 文件源码
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
项目:aws-ops-automator    作者:awslabs    | 项目源码 | 文件源码
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)
项目:aws-ops-automator    作者:awslabs    | 项目源码 | 文件源码
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)
项目:epg-dk.bundle    作者:ukdtom    | 项目源码 | 文件源码
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))
项目:epg-dk.bundle    作者:ukdtom    | 项目源码 | 文件源码
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')
项目:epg-dk.bundle    作者:ukdtom    | 项目源码 | 文件源码
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)