Python datetime.datetime.timezone() Examples

The following are 30 code examples of datetime.datetime.timezone(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module datetime.datetime , or try the search function .
Example #1
Source File: _compat.py    From tomlkit with MIT License 7 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
Source File: test_timezones.py    From twitter-stock-recommendation with 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 #3
Source File: test_timezones.py    From twitter-stock-recommendation with 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 #4
Source File: test_timezones.py    From coffeegrindsize with 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 #5
Source File: test_timezones.py    From coffeegrindsize with 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 #6
Source File: util.py    From asn1crypto with 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 #7
Source File: util.py    From asn1crypto with 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 #8
Source File: test_timezones.py    From predictive-maintenance-using-machine-learning with 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 #9
Source File: test_timezones.py    From predictive-maintenance-using-machine-learning with 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 #10
Source File: test_catalina_10_15_5.py    From osxphotos with MIT License 6 votes vote down vote up
def test_attributes():
    import datetime
    import osxphotos

    photosdb = osxphotos.PhotosDB(dbfile=PHOTOS_DB)
    photos = photosdb.photos(uuid=["D79B8D77-BFFC-460B-9312-034F2877D35B"])
    assert len(photos) == 1
    p = photos[0]
    assert p.keywords == ["Kids"]
    assert p.original_filename == "Pumkins2.jpg"
    assert p.filename == "D79B8D77-BFFC-460B-9312-034F2877D35B.jpeg"
    assert p.date == datetime.datetime(
        2018, 9, 28, 16, 7, 7, 0, datetime.timezone(datetime.timedelta(seconds=-14400))
    )
    assert p.description == "Girl holding pumpkin"
    assert p.title == "I found one!"
    assert sorted(p.albums) == ["Pumpkin Farm", "Test Album"]
    assert p.persons == ["Katie"]
    assert p.path.endswith(
        "tests/Test-10.15.5.photoslibrary/originals/D/D79B8D77-BFFC-460B-9312-034F2877D35B.jpeg"
    )
    assert p.ismissing == False 
Example #11
Source File: test_mojave_10_14_6.py    From osxphotos with MIT License 6 votes vote down vote up
def test_attributes():
    import datetime
    import osxphotos

    photosdb = osxphotos.PhotosDB(dbfile=PHOTOS_DB)
    photos = photosdb.photos(uuid=["15uNd7%8RguTEgNPKHfTWw"])
    assert len(photos) == 1
    p = photos[0]
    assert p.keywords == ["Kids"]
    assert p.original_filename == "Pumkins2.jpg"
    assert p.filename == "Pumkins2.jpg"
    assert p.date == datetime.datetime(
        2018, 9, 28, 16, 7, 7, 0, datetime.timezone(datetime.timedelta(seconds=-14400))
    )
    assert p.description == "Girl holding pumpkin"
    assert p.title == "I found one!"
    assert sorted(p.albums) == sorted(
        ["Pumpkin Farm", "AlbumInFolder", "Test Album (1)"]
    )
    assert p.persons == ["Katie"]
    assert p.path.endswith(
        "/tests/Test-10.14.6.photoslibrary/Masters/2019/07/27/20190727-131650/Pumkins2.jpg"
    )
    assert p.ismissing == False 
Example #12
Source File: _compat.py    From pipenv with 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 #13
Source File: test_timezones.py    From recruit with 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
Source File: test_timezones.py    From recruit with 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
Source File: test_timezones.py    From vnpy_crypto with 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
Source File: util.py    From teleport with Apache License 2.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 #17
Source File: test_timezones.py    From vnpy_crypto with 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 #18
Source File: util.py    From teleport with Apache License 2.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 #19
Source File: helpers.py    From kytos with 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 #20
Source File: _compat.py    From tomlkit with MIT License 5 votes vote down vote up
def __eq__(self, other):
            if type(other) != timezone:
                return False
            return self._offset == other._offset 
Example #21
Source File: util.py    From asn1crypto with 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 #22
Source File: util.py    From asn1crypto with 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 #23
Source File: util.py    From asn1crypto with 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 #24
Source File: util.py    From asn1crypto with 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 #25
Source File: helpers.py    From kytos with 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 #26
Source File: _compat.py    From pipenv with MIT License 5 votes vote down vote up
def __eq__(self, other):
            if type(other) != timezone:
                return False
            return self._offset == other._offset 
Example #27
Source File: util.py    From teleport with Apache License 2.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 #28
Source File: util.py    From teleport with Apache License 2.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 #29
Source File: test_catalina_10_15_5.py    From osxphotos with MIT License 5 votes vote down vote up
def test_date_modified_invalid():
    """ Test date modified is invalid """
    from datetime import datetime, timedelta, timezone
    import osxphotos

    photosdb = osxphotos.PhotosDB(dbfile=PHOTOS_DB)
    photos = photosdb.photos(uuid=[UUID_DICT["date_invalid"]])
    assert len(photos) == 1
    p = photos[0]
    assert p.date_modified is None 
Example #30
Source File: test_catalina_10_15_5.py    From osxphotos with MIT License 5 votes vote down vote up
def test_date_invalid():
    """ Test date is invalid """
    from datetime import datetime, timedelta, timezone
    import osxphotos

    photosdb = osxphotos.PhotosDB(dbfile=PHOTOS_DB)
    photos = photosdb.photos(uuid=[UUID_DICT["date_invalid"]])
    assert len(photos) == 1
    p = photos[0]
    delta = timedelta(seconds=p.tzoffset)
    tz = timezone(delta)
    assert p.date == datetime(1970, 1, 1).astimezone(tz=tz)