Python datetime.datetime.timezone() Examples

The following are code examples for showing how to use datetime.datetime.timezone(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: tomlkit   Author: sdispater   File: _compat.py    MIT License 6 votes vote down vote up
def __repr__(self):
            """Convert to formal string, for repr().

            >>> tz = timezone.utc
            >>> repr(tz)
            'datetime.timezone.utc'
            >>> tz = timezone(timedelta(hours=-5), 'EST')
            >>> repr(tz)
            "datetime.timezone(datetime.timedelta(-1, 68400), 'EST')"
            """
            if self is self.utc:
                return "datetime.timezone.utc"
            if self._name is None:
                return "%s.%s(%r)" % (
                    self.__class__.__module__,
                    self.__class__.__name__,
                    self._offset,
                )
            return "%s.%s(%r, %r)" % (
                self.__class__.__module__,
                self.__class__.__name__,
                self._offset,
                self._name,
            ) 
Example 2
Project: recruit   Author: Frank-qlu   File: test_timezones.py    Apache License 2.0 6 votes vote down vote up
def test_normalize_tz_local(self, timezone):
        # GH#13459
        with tm.set_timezone(timezone):
            rng = date_range('1/1/2000 9:30', periods=10, freq='D',
                             tz=tzlocal())

            result = rng.normalize()
            expected = date_range('1/1/2000', periods=10, freq='D',
                                  tz=tzlocal())
            tm.assert_index_equal(result, expected)

            assert result.is_normalized
            assert not rng.is_normalized

    # ------------------------------------------------------------
    # DatetimeIndex.__new__ 
Example 3
Project: recruit   Author: Frank-qlu   File: test_timezones.py    Apache License 2.0 6 votes vote down vote up
def test_dti_tz_constructors(self, tzstr):
        """ Test different DatetimeIndex constructions with timezone
        Follow-up of GH#4229
        """

        arr = ['11/10/2005 08:00:00', '11/10/2005 09:00:00']

        idx1 = to_datetime(arr).tz_localize(tzstr)
        idx2 = pd.date_range(start="2005-11-10 08:00:00", freq='H', periods=2,
                             tz=tzstr)
        idx3 = DatetimeIndex(arr, tz=tzstr)
        idx4 = DatetimeIndex(np.array(arr), tz=tzstr)

        for other in [idx2, idx3, idx4]:
            tm.assert_index_equal(idx1, other)

    # -------------------------------------------------------------
    # Unsorted 
Example 4
Project: FUTU_Stop_Loss   Author: BigtoC   File: test_timezones.py    MIT License 6 votes vote down vote up
def test_normalize_tz_local(self, timezone):
        # GH#13459
        with tm.set_timezone(timezone):
            rng = date_range('1/1/2000 9:30', periods=10, freq='D',
                             tz=tzlocal())

            result = rng.normalize()
            expected = date_range('1/1/2000', periods=10, freq='D',
                                  tz=tzlocal())
            tm.assert_index_equal(result, expected)

            assert result.is_normalized
            assert not rng.is_normalized

    # ------------------------------------------------------------
    # DatetimeIndex.__new__ 
Example 5
Project: FUTU_Stop_Loss   Author: BigtoC   File: test_timezones.py    MIT License 6 votes vote down vote up
def test_dti_tz_constructors(self, tzstr):
        """ Test different DatetimeIndex constructions with timezone
        Follow-up of GH#4229
        """

        arr = ['11/10/2005 08:00:00', '11/10/2005 09:00:00']

        idx1 = to_datetime(arr).tz_localize(tzstr)
        idx2 = DatetimeIndex(start="2005-11-10 08:00:00", freq='H', periods=2,
                             tz=tzstr)
        idx3 = DatetimeIndex(arr, tz=tzstr)
        idx4 = DatetimeIndex(np.array(arr), tz=tzstr)

        for other in [idx2, idx3, idx4]:
            tm.assert_index_equal(idx1, other)

    # -------------------------------------------------------------
    # Unsorted 
Example 6
Project: banruo   Author: yingshang   File: util.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, offset, name=None):
            """
            :param offset:
                A timedelta with this timezone's offset from UTC

            :param name:
                Name of the timezone; if None, generate one.
            """

            if not timedelta(hours=-24) < offset < timedelta(hours=24):
                raise ValueError('Offset must be in [-23:59, 23:59]')

            if offset.seconds % 60 or offset.microseconds:
                raise ValueError('Offset must be full minutes')

            self._offset = offset

            if name is not None:
                self._name = name
            elif not offset:
                self._name = 'UTC'
            else:
                self._name = 'UTC' + _format_offset(offset) 
Example 7
Project: banruo   Author: yingshang   File: util.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def create_timezone(offset):
    """
    Returns a new datetime.timezone object with the given offset.
    Uses cached objects if possible.

    :param offset:
        A datetime.timedelta object; It needs to be in full minutes and between -23:59 and +23:59.

    :return:
        A datetime.timezone object
    """

    try:
        tz = _timezone_cache[offset]
    except KeyError:
        tz = _timezone_cache[offset] = timezone(offset)
    return tz 
Example 8
Project: vnpy_crypto   Author: birforce   File: test_timezones.py    MIT License 6 votes vote down vote up
def test_normalize_tz_local(self, timezone):
        # GH#13459
        with tm.set_timezone(timezone):
            rng = date_range('1/1/2000 9:30', periods=10, freq='D',
                             tz=tzlocal())

            result = rng.normalize()
            expected = date_range('1/1/2000', periods=10, freq='D',
                                  tz=tzlocal())
            tm.assert_index_equal(result, expected)

            assert result.is_normalized
            assert not rng.is_normalized

    # ------------------------------------------------------------
    # DatetimeIndex.__new__ 
Example 9
Project: vnpy_crypto   Author: birforce   File: test_timezones.py    MIT License 6 votes vote down vote up
def test_dti_tz_constructors(self, tzstr):
        """ Test different DatetimeIndex constructions with timezone
        Follow-up of GH#4229
        """

        arr = ['11/10/2005 08:00:00', '11/10/2005 09:00:00']

        idx1 = to_datetime(arr).tz_localize(tzstr)
        idx2 = DatetimeIndex(start="2005-11-10 08:00:00", freq='H', periods=2,
                             tz=tzstr)
        idx3 = DatetimeIndex(arr, tz=tzstr)
        idx4 = DatetimeIndex(np.array(arr), tz=tzstr)

        for other in [idx2, idx3, idx4]:
            tm.assert_index_equal(idx1, other)

    # -------------------------------------------------------------
    # Unsorted 
Example 10
Project: pipenv   Author: pypa   File: _compat.py    MIT License 6 votes vote down vote up
def __repr__(self):
            """Convert to formal string, for repr().

            >>> tz = timezone.utc
            >>> repr(tz)
            'datetime.timezone.utc'
            >>> tz = timezone(timedelta(hours=-5), 'EST')
            >>> repr(tz)
            "datetime.timezone(datetime.timedelta(-1, 68400), 'EST')"
            """
            if self is self.utc:
                return "datetime.timezone.utc"
            if self._name is None:
                return "%s.%s(%r)" % (
                    self.__class__.__module__,
                    self.__class__.__qualname__,
                    self._offset,
                )
            return "%s.%s(%r, %r)" % (
                self.__class__.__module__,
                self.__class__.__qualname__,
                self._offset,
                self._name,
            ) 
Example 11
Project: predictive-maintenance-using-machine-learning   Author: awslabs   File: test_timezones.py    Apache License 2.0 6 votes vote down vote up
def test_normalize_tz_local(self, timezone):
        # GH#13459
        with tm.set_timezone(timezone):
            rng = date_range('1/1/2000 9:30', periods=10, freq='D',
                             tz=tzlocal())

            result = rng.normalize()
            expected = date_range('1/1/2000', periods=10, freq='D',
                                  tz=tzlocal())
            tm.assert_index_equal(result, expected)

            assert result.is_normalized
            assert not rng.is_normalized

    # ------------------------------------------------------------
    # DatetimeIndex.__new__ 
Example 12
Project: predictive-maintenance-using-machine-learning   Author: awslabs   File: test_timezones.py    Apache License 2.0 6 votes vote down vote up
def test_dti_tz_constructors(self, tzstr):
        """ Test different DatetimeIndex constructions with timezone
        Follow-up of GH#4229
        """

        arr = ['11/10/2005 08:00:00', '11/10/2005 09:00:00']

        idx1 = to_datetime(arr).tz_localize(tzstr)
        idx2 = pd.date_range(start="2005-11-10 08:00:00", freq='H', periods=2,
                             tz=tzstr)
        idx3 = DatetimeIndex(arr, tz=tzstr)
        idx4 = DatetimeIndex(np.array(arr), tz=tzstr)

        for other in [idx2, idx3, idx4]:
            tm.assert_index_equal(idx1, other)

    # -------------------------------------------------------------
    # Unsorted 
Example 13
Project: fund   Author: Frank-qlu   File: test_timezones.py    Apache License 2.0 6 votes vote down vote up
def test_normalize_tz_local(self, timezone):
        # GH#13459
        with tm.set_timezone(timezone):
            rng = date_range('1/1/2000 9:30', periods=10, freq='D',
                             tz=tzlocal())

            result = rng.normalize()
            expected = date_range('1/1/2000', periods=10, freq='D',
                                  tz=tzlocal())
            tm.assert_index_equal(result, expected)

            assert result.is_normalized
            assert not rng.is_normalized

    # ------------------------------------------------------------
    # DatetimeIndex.__new__ 
Example 14
Project: fund   Author: Frank-qlu   File: test_timezones.py    Apache License 2.0 6 votes vote down vote up
def test_dti_tz_constructors(self, tzstr):
        """ Test different DatetimeIndex constructions with timezone
        Follow-up of GH#4229
        """

        arr = ['11/10/2005 08:00:00', '11/10/2005 09:00:00']

        idx1 = to_datetime(arr).tz_localize(tzstr)
        idx2 = pd.date_range(start="2005-11-10 08:00:00", freq='H', periods=2,
                             tz=tzstr)
        idx3 = DatetimeIndex(arr, tz=tzstr)
        idx4 = DatetimeIndex(np.array(arr), tz=tzstr)

        for other in [idx2, idx3, idx4]:
            tm.assert_index_equal(idx1, other)

    # -------------------------------------------------------------
    # Unsorted 
Example 15
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_timezones.py    MIT License 6 votes vote down vote up
def test_normalize_tz_local(self, timezone):
        # GH#13459
        with tm.set_timezone(timezone):
            rng = date_range('1/1/2000 9:30', periods=10, freq='D',
                             tz=tzlocal())

            result = rng.normalize()
            expected = date_range('1/1/2000', periods=10, freq='D',
                                  tz=tzlocal())
            tm.assert_index_equal(result, expected)

            assert result.is_normalized
            assert not rng.is_normalized

    # ------------------------------------------------------------
    # DatetimeIndex.__new__ 
Example 16
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_timezones.py    MIT License 6 votes vote down vote up
def test_dti_tz_constructors(self, tzstr):
        """ Test different DatetimeIndex constructions with timezone
        Follow-up of GH#4229
        """

        arr = ['11/10/2005 08:00:00', '11/10/2005 09:00:00']

        idx1 = to_datetime(arr).tz_localize(tzstr)
        idx2 = pd.date_range(start="2005-11-10 08:00:00", freq='H', periods=2,
                             tz=tzstr)
        idx3 = DatetimeIndex(arr, tz=tzstr)
        idx4 = DatetimeIndex(np.array(arr), tz=tzstr)

        for other in [idx2, idx3, idx4]:
            tm.assert_index_equal(idx1, other)

    # -------------------------------------------------------------
    # Unsorted 
Example 17
Project: fund-rank-dashboard   Author: 1pani   File: test_timezones.py    Apache License 2.0 6 votes vote down vote up
def test_normalize_tz_local(self, timezone):
        # GH#13459
        with tm.set_timezone(timezone):
            rng = date_range('1/1/2000 9:30', periods=10, freq='D',
                             tz=tzlocal())

            result = rng.normalize()
            expected = date_range('1/1/2000', periods=10, freq='D',
                                  tz=tzlocal())
            tm.assert_index_equal(result, expected)

            assert result.is_normalized
            assert not rng.is_normalized

    # ------------------------------------------------------------
    # DatetimeIndex.__new__ 
Example 18
Project: fund-rank-dashboard   Author: 1pani   File: test_timezones.py    Apache License 2.0 6 votes vote down vote up
def test_dti_tz_constructors(self, tzstr):
        """ Test different DatetimeIndex constructions with timezone
        Follow-up of GH#4229
        """

        arr = ['11/10/2005 08:00:00', '11/10/2005 09:00:00']

        idx1 = to_datetime(arr).tz_localize(tzstr)
        idx2 = DatetimeIndex(start="2005-11-10 08:00:00", freq='H', periods=2,
                             tz=tzstr)
        idx3 = DatetimeIndex(arr, tz=tzstr)
        idx4 = DatetimeIndex(np.array(arr), tz=tzstr)

        for other in [idx2, idx3, idx4]:
            tm.assert_index_equal(idx1, other)

    # -------------------------------------------------------------
    # Unsorted 
Example 19
Project: asn1crypto   Author: wbond   File: util.py    MIT License 6 votes vote down vote up
def __init__(self, offset, name=None):
            """
            :param offset:
                A timedelta with this timezone's offset from UTC

            :param name:
                Name of the timezone; if None, generate one.
            """

            if not timedelta(hours=-24) < offset < timedelta(hours=24):
                raise ValueError('Offset must be in [-23:59, 23:59]')

            if offset.seconds % 60 or offset.microseconds:
                raise ValueError('Offset must be full minutes')

            self._offset = offset

            if name is not None:
                self._name = name
            elif not offset:
                self._name = 'UTC'
            else:
                self._name = 'UTC' + _format_offset(offset) 
Example 20
Project: asn1crypto   Author: wbond   File: util.py    MIT License 6 votes vote down vote up
def create_timezone(offset):
    """
    Returns a new datetime.timezone object with the given offset.
    Uses cached objects if possible.

    :param offset:
        A datetime.timedelta object; It needs to be in full minutes and between -23:59 and +23:59.

    :return:
        A datetime.timezone object
    """

    try:
        tz = _timezone_cache[offset]
    except KeyError:
        tz = _timezone_cache[offset] = timezone(offset)
    return tz 
Example 21
Project: tomlkit   Author: sdispater   File: _compat.py    MIT License 5 votes vote down vote up
def __eq__(self, other):
            if type(other) != timezone:
                return False
            return self._offset == other._offset 
Example 22
Project: banruo   Author: yingshang   File: util.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def __eq__(self, other):
            """
            Compare two timezones

            :param other:
                The other timezone to compare to

            :return:
                A boolean
            """

            if type(other) != timezone:
                return False
            return self._offset == other._offset 
Example 23
Project: banruo   Author: yingshang   File: util.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def tzname(self, dt):
            """
            :param dt:
                A datetime object; ignored.

            :return:
                Name of this timezone
            """

            return self._name 
Example 24
Project: banruo   Author: yingshang   File: util.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def tzinfo(self):
        """
        :return:
            If object is timezone aware, a datetime.tzinfo object, else None.
        """

        return self._y2k.tzinfo 
Example 25
Project: banruo   Author: yingshang   File: util.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def astimezone(self, tz):
        """
        Convert this extended_datetime to another timezone.

        :param tz:
            A datetime.tzinfo object.

        :return:
            A new extended_datetime or datetime.datetime object
        """

        return extended_datetime.from_y2k(self._y2k.astimezone(tz)) 
Example 26
Project: ibstract   Author: jesseliu0   File: marketdata.py    MIT License 5 votes vote down vote up
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 
Example 27
Project: pipenv   Author: pypa   File: _compat.py    MIT License 5 votes vote down vote up
def __eq__(self, other):
            if type(other) != timezone:
                return False
            return self._offset == other._offset 
Example 28
Project: kytos   Author: kytos   File: helpers.py    MIT License 5 votes vote down vote up
def now(tzone=timezone.utc):
    """Return the current datetime (default to UTC).

    Args:
        tzone (datetime.timezone): Specific time zone used in datetime.

    Returns:
        datetime.datetime.now: Date time with specific time zone.

    """
    return datetime.now(tzone) 
Example 29
Project: kytos   Author: kytos   File: helpers.py    MIT License 5 votes vote down vote up
def get_time(data=None):
    """Receive a dictionary or a string and return a datatime instance.

    data = {"year": 2006,
            "month": 11,
            "day": 21,
            "hour": 16,
            "minute": 30 ,
            "second": 00}

    or

    data = "21/11/06 16:30:00"

    2018-04-17T17:13:50Z

    Args:
        data (str, dict): python dict or string to be converted to datetime

    Returns:
        datetime: datetime instance.

    """
    if isinstance(data, str):
        date = datetime.strptime(data, "%Y-%m-%dT%H:%M:%S")
    elif isinstance(data, dict):
        date = datetime(**data)
    else:
        return None
    return date.replace(tzinfo=timezone.utc) 
Example 30
Project: asn1crypto   Author: wbond   File: util.py    MIT License 5 votes vote down vote up
def __eq__(self, other):
            """
            Compare two timezones

            :param other:
                The other timezone to compare to

            :return:
                A boolean
            """

            if type(other) != timezone:
                return False
            return self._offset == other._offset 
Example 31
Project: asn1crypto   Author: wbond   File: util.py    MIT License 5 votes vote down vote up
def tzname(self, dt):
            """
            :param dt:
                A datetime object; ignored.

            :return:
                Name of this timezone
            """

            return self._name 
Example 32
Project: asn1crypto   Author: wbond   File: util.py    MIT License 5 votes vote down vote up
def tzinfo(self):
        """
        :return:
            If object is timezone aware, a datetime.tzinfo object, else None.
        """

        return self._y2k.tzinfo 
Example 33
Project: asn1crypto   Author: wbond   File: util.py    MIT License 5 votes vote down vote up
def astimezone(self, tz):
        """
        Convert this extended_datetime to another timezone.

        :param tz:
            A datetime.tzinfo object.

        :return:
            A new extended_datetime or datetime.datetime object
        """

        return extended_datetime.from_y2k(self._y2k.astimezone(tz)) 
Example 34
Project: ibstract   Author: jesseliu0   File: marketdata.py    MIT License 4 votes vote down vote up
def _standardize_index(
            self, df_in: pd.DataFrame, symbol: str=None, datatype: str=None,
            barsize: str=None, tz: str=None):
        """Normalize input DataFrame index to MarketDataBlock standard.
        """
        # Add or starndardize index names in the input.
        if isinstance(df_in.index, pd.MultiIndex):
            df_in.reset_index(inplace=True)

        # Rename ambiguous column names.
        df_in.columns = [
            col_rename.get(col.strip().lower(), col.strip().lower())
            for col in df_in.columns]

        # Insert Symbol, DataType, Barsize columns from arguments if not
        # found in the input dataframe.
        for col in MarketDataBlock.data_index:
            if col not in df_in.columns:
                if locals().get(col.lower(), None) is None:
                    raise KeyError(
                        'No {0} argument and no {0} column in the DataFrame.'
                        .format(col))
                df_in.insert(0, col, locals()[col.lower()])

        # Convert datetime strings to pandas DatetimeIndex
        df_in['TickerTime'] = pd.DatetimeIndex(
            df_in['TickerTime'].apply(pd.Timestamp))

        # Standardize BarSize strings
        df_in['BarSize'] = df_in['BarSize'].map(timedur_standardize)

        # Set index to class-defined MultiIndex
        df_in.set_index(MarketDataBlock.data_index, inplace=True)

        # Set time zone so all DatetimeIndex are tz-aware
        df_in_tz = df_in.index.levels[self.__class__.dtlevel].tz
        if df_in_tz is None or isinstance(df_in_tz, timezone) or \
           isinstance(df_in_tz, pytz._FixedOffset):
            # Input df has naive time index, or tzinfo is not pytz.timezone()
            if tz is None:
                raise ValueError(
                    'Argument tz=None, and TickerTime.tzinfo is None(naive),'
                    'datetime.timezone, or pytz._FixedOffset.')
            if df_in_tz is None:
                df_in = df_in.tz_localize(tz, level=self.__class__.dtlevel)
            else:
                df_in = df_in.tz_convert(tz, level=self.__class__.dtlevel)

        return df_in