Python dateutil.tz.tzoffset() Examples

The following are 30 code examples of dateutil.tz.tzoffset(). 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 dateutil.tz , or try the search function .
Example #1
Source File: isoparser.py    From pipenv with MIT License 6 votes vote down vote up
def parse_tzstr(self, tzstr, zero_as_utc=True):
        """
        Parse a valid ISO time zone string.

        See :func:`isoparser.isoparse` for details on supported formats.

        :param tzstr:
            A string representing an ISO time zone offset

        :param zero_as_utc:
            Whether to return :class:`dateutil.tz.tzutc` for zero-offset zones

        :return:
            Returns :class:`dateutil.tz.tzoffset` for offsets and
            :class:`dateutil.tz.tzutc` for ``Z`` and (if ``zero_as_utc`` is
            specified) offsets equivalent to UTC.
        """
        return self._parse_tzstr(tzstr, zero_as_utc=zero_as_utc)

    # Constants 
Example #2
Source File: isoparser.py    From aws-extender with MIT License 6 votes vote down vote up
def parse_tzstr(self, tzstr, zero_as_utc=True):
        """
        Parse a valid ISO time zone string.

        See :func:`isoparser.isoparse` for details on supported formats.

        :param tzstr:
            A string representing an ISO time zone offset

        :param zero_as_utc:
            Whether to return :class:`dateutil.tz.tzutc` for zero-offset zones

        :return:
            Returns :class:`dateutil.tz.tzoffset` for offsets and
            :class:`dateutil.tz.tzutc` for ``Z`` and (if ``zero_as_utc`` is
            specified) offsets equivalent to UTC.
        """
        return self._parse_tzstr(tzstr, zero_as_utc=zero_as_utc)

    # Constants 
Example #3
Source File: test_datetime_fields.py    From jsonmodels with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_datetime_field_parse_value():

    field = fields.DateTimeField()

    assert (
        datetime.datetime(2014, 4, 21, 12, 45, 56) ==
        field.parse_value('2014-04-21T12:45:56')
    )
    assert (
        datetime.datetime(
            2014, 4, 21, 12, 45, 56, tzinfo=tzoffset(None, 7200)) ==
        field.parse_value('2014-04-21T12:45:56+02:00')
    )

    with pytest.raises(ValueError):
        field.parse_value('not a datetime') 
Example #4
Source File: test_infofile.py    From barman with GNU General Public License v3.0 6 votes vote down vote up
def test_load_datetime_tz():
    """
    Unit test for load_datetime_tz function

    This test covers all load_datetime_tz code with correct parameters
    and checks that a ValueError is raised when called with a bad parameter.
    """
    # try to load a tz-less timestamp
    assert load_datetime_tz("2012-12-15 10:14:51.898000") == \
        datetime(2012, 12, 15, 10, 14, 51, 898000,
                 tzinfo=tzlocal())

    # try to load a tz-aware timestamp
    assert load_datetime_tz("2012-12-15 10:14:51.898000 +0100") == \
        datetime(2012, 12, 15, 10, 14, 51, 898000,
                 tzinfo=tzoffset('GMT+1', 3600))

    # try to load an incorrect date
    with pytest.raises(ValueError):
        load_datetime_tz("Invalid datetime")


# noinspection PyMethodMayBeStatic 
Example #5
Source File: isoparser.py    From AWS-Transit-Gateway-Demo-MultiAccount with MIT License 6 votes vote down vote up
def parse_tzstr(self, tzstr, zero_as_utc=True):
        """
        Parse a valid ISO time zone string.

        See :func:`isoparser.isoparse` for details on supported formats.

        :param tzstr:
            A string representing an ISO time zone offset

        :param zero_as_utc:
            Whether to return :class:`dateutil.tz.tzutc` for zero-offset zones

        :return:
            Returns :class:`dateutil.tz.tzoffset` for offsets and
            :class:`dateutil.tz.tzutc` for ``Z`` and (if ``zero_as_utc`` is
            specified) offsets equivalent to UTC.
        """
        return self._parse_tzstr(tzstr, zero_as_utc=zero_as_utc)

    # Constants 
Example #6
Source File: test_imports.py    From plugin.video.emby with GNU General Public License v3.0 6 votes vote down vote up
def testTzAll(self):
        from dateutil.tz import tzutc
        from dateutil.tz import tzoffset
        from dateutil.tz import tzlocal
        from dateutil.tz import tzfile
        from dateutil.tz import tzrange
        from dateutil.tz import tzstr
        from dateutil.tz import tzical
        from dateutil.tz import gettz
        from dateutil.tz import tzwin
        from dateutil.tz import tzwinlocal
        from dateutil.tz import UTC
        from dateutil.tz import datetime_ambiguous
        from dateutil.tz import datetime_exists
        from dateutil.tz import resolve_imaginary

        tz_all = ["tzutc", "tzoffset", "tzlocal", "tzfile", "tzrange",
                  "tzstr", "tzical", "gettz", "datetime_ambiguous",
                  "datetime_exists", "resolve_imaginary", "UTC"]

        tz_all += ["tzwin", "tzwinlocal"] if sys.platform.startswith("win") else []
        lvars = locals()

        for var in tz_all:
            self.assertIsNot(lvars[var], None) 
Example #7
Source File: test_utils.py    From atoma with MIT License 6 votes vote down vote up
def test_try_parse_date():
    expected = datetime(
        2018, 11, 30, 17, 0, tzinfo=timezone(timedelta(seconds=32400))
    )
    assert try_parse_date('Fri, 30 Nov 2018 17:00:00 +0900') == expected

    assert try_parse_date('Fri, 30 Nov 2018 17:00:00:00 +0900') is None

    expected = datetime(2018, 11, 30, 17, 0, tzinfo=timezone.utc)
    assert try_parse_date('Fri, 30 Nov 2018 17:00:00 GMT') == expected
    assert try_parse_date('Fri, 30 Nov 2018 17:00:00 UT') == expected
    assert try_parse_date('Fri, 30 Nov 2018 17:00:00 Z') == expected
    assert try_parse_date('Fri, 30 Nov 2018 17:00:00') == expected

    expected = datetime(2018, 11, 30, 17, 0, tzinfo=tzoffset('PST', -28800))
    assert try_parse_date('Fri, 30 Nov 2018 17:00:00 PST') == expected

    expected = datetime(2018, 10, 10, 18, 0, tzinfo=timezone.utc)
    assert try_parse_date('Web, 10 Oct 2018 18:00:00 +0000') == expected 
Example #8
Source File: isoparser.py    From bash-lambda-layer with MIT License 6 votes vote down vote up
def parse_tzstr(self, tzstr, zero_as_utc=True):
        """
        Parse a valid ISO time zone string.

        See :func:`isoparser.isoparse` for details on supported formats.

        :param tzstr:
            A string representing an ISO time zone offset

        :param zero_as_utc:
            Whether to return :class:`dateutil.tz.tzutc` for zero-offset zones

        :return:
            Returns :class:`dateutil.tz.tzoffset` for offsets and
            :class:`dateutil.tz.tzutc` for ``Z`` and (if ``zero_as_utc`` is
            specified) offsets equivalent to UTC.
        """
        return self._parse_tzstr(tzstr, zero_as_utc=zero_as_utc)

    # Constants 
Example #9
Source File: isoparser.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def parse_tzstr(self, tzstr, zero_as_utc=True):
        """
        Parse a valid ISO time zone string.

        See :func:`isoparser.isoparse` for details on supported formats.

        :param tzstr:
            A string representing an ISO time zone offset

        :param zero_as_utc:
            Whether to return :class:`dateutil.tz.tzutc` for zero-offset zones

        :return:
            Returns :class:`dateutil.tz.tzoffset` for offsets and
            :class:`dateutil.tz.tzutc` for ``Z`` and (if ``zero_as_utc`` is
            specified) offsets equivalent to UTC.
        """
        return self._parse_tzstr(tzstr, zero_as_utc=zero_as_utc)

    # Constants 
Example #10
Source File: isoparser.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
def parse_tzstr(self, tzstr, zero_as_utc=True):
        """
        Parse a valid ISO time zone string.

        See :func:`isoparser.isoparse` for details on supported formats.

        :param tzstr:
            A string representing an ISO time zone offset

        :param zero_as_utc:
            Whether to return :class:`dateutil.tz.tzutc` for zero-offset zones

        :return:
            Returns :class:`dateutil.tz.tzoffset` for offsets and
            :class:`dateutil.tz.tzutc` for ``Z`` and (if ``zero_as_utc`` is
            specified) offsets equivalent to UTC.
        """
        return self._parse_tzstr(tzstr, zero_as_utc=zero_as_utc)

    # Constants 
Example #11
Source File: isoparser.py    From recruit with Apache License 2.0 6 votes vote down vote up
def parse_tzstr(self, tzstr, zero_as_utc=True):
        """
        Parse a valid ISO time zone string.

        See :func:`isoparser.isoparse` for details on supported formats.

        :param tzstr:
            A string representing an ISO time zone offset

        :param zero_as_utc:
            Whether to return :class:`dateutil.tz.tzutc` for zero-offset zones

        :return:
            Returns :class:`dateutil.tz.tzoffset` for offsets and
            :class:`dateutil.tz.tzutc` for ``Z`` and (if ``zero_as_utc`` is
            specified) offsets equivalent to UTC.
        """
        return self._parse_tzstr(tzstr, zero_as_utc=zero_as_utc)

    # Constants 
Example #12
Source File: isoparser.py    From AWS-Transit-Gateway-Demo-MultiAccount with MIT License 6 votes vote down vote up
def parse_tzstr(self, tzstr, zero_as_utc=True):
        """
        Parse a valid ISO time zone string.

        See :func:`isoparser.isoparse` for details on supported formats.

        :param tzstr:
            A string representing an ISO time zone offset

        :param zero_as_utc:
            Whether to return :class:`dateutil.tz.tzutc` for zero-offset zones

        :return:
            Returns :class:`dateutil.tz.tzoffset` for offsets and
            :class:`dateutil.tz.tzutc` for ``Z`` and (if ``zero_as_utc`` is
            specified) offsets equivalent to UTC.
        """
        return self._parse_tzstr(tzstr, zero_as_utc=zero_as_utc)

    # Constants 
Example #13
Source File: isoparser.py    From Mastering-Elasticsearch-7.0 with MIT License 6 votes vote down vote up
def parse_tzstr(self, tzstr, zero_as_utc=True):
        """
        Parse a valid ISO time zone string.

        See :func:`isoparser.isoparse` for details on supported formats.

        :param tzstr:
            A string representing an ISO time zone offset

        :param zero_as_utc:
            Whether to return :class:`dateutil.tz.tzutc` for zero-offset zones

        :return:
            Returns :class:`dateutil.tz.tzoffset` for offsets and
            :class:`dateutil.tz.tzutc` for ``Z`` and (if ``zero_as_utc`` is
            specified) offsets equivalent to UTC.
        """
        return self._parse_tzstr(tzstr, zero_as_utc=zero_as_utc)

    # Constants 
Example #14
Source File: isoparser.py    From deepWordBug with Apache License 2.0 6 votes vote down vote up
def parse_tzstr(self, tzstr, zero_as_utc=True):
        """
        Parse a valid ISO time zone string.

        See :func:`isoparser.isoparse` for details on supported formats.

        :param tzstr:
            A string representing an ISO time zone offset

        :param zero_as_utc:
            Whether to return :class:`dateutil.tz.tzutc` for zero-offset zones

        :return:
            Returns :class:`dateutil.tz.tzoffset` for offsets and
            :class:`dateutil.tz.tzutc` for ``Z`` and (if ``zero_as_utc`` is
            specified) offsets equivalent to UTC.
        """
        return self._parse_tzstr(tzstr, zero_as_utc=zero_as_utc)

    # Constants 
Example #15
Source File: test_domain.py    From hcloud-python with MIT License 5 votes vote down vote up
def test_created_is_datetime(self):
        floatingIP = FloatingIP(id=1, created="2016-01-30T23:50+00:00")
        assert floatingIP.created == datetime.datetime(2016, 1, 30, 23, 50, tzinfo=tzoffset(None, 0)) 
Example #16
Source File: test_domain.py    From hcloud-python with MIT License 5 votes vote down vote up
def test_created_is_datetime(self):
        sshKey = SSHKey(id=1, created="2016-01-30T23:50+00:00")
        assert sshKey.created == datetime.datetime(2016, 1, 30, 23, 50, tzinfo=tzoffset(None, 0)) 
Example #17
Source File: isoparser.py    From bash-lambda-layer with MIT License 5 votes vote down vote up
def _parse_tzstr(self, tzstr, zero_as_utc=True):
        if tzstr == b'Z' or tzstr == b'z':
            return tz.tzutc()

        if len(tzstr) not in {3, 5, 6}:
            raise ValueError('Time zone offset must be 1, 3, 5 or 6 characters')

        if tzstr[0:1] == b'-':
            mult = -1
        elif tzstr[0:1] == b'+':
            mult = 1
        else:
            raise ValueError('Time zone offset requires sign')

        hours = int(tzstr[1:3])
        if len(tzstr) == 3:
            minutes = 0
        else:
            minutes = int(tzstr[(4 if tzstr[3:4] == self._TIME_SEP else 3):])

        if zero_as_utc and hours == 0 and minutes == 0:
            return tz.tzutc()
        else:
            if minutes > 59:
                raise ValueError('Invalid minutes in time zone offset')

            if hours > 23:
                raise ValueError('Invalid hours in time zone offset')

            return tz.tzoffset(None, mult * (hours * 60 + minutes) * 60) 
Example #18
Source File: isoparser.py    From aws-extender with MIT License 5 votes vote down vote up
def _parse_tzstr(self, tzstr, zero_as_utc=True):
        if tzstr == b'Z':
            return tz.tzutc()

        if len(tzstr) not in {3, 5, 6}:
            raise ValueError('Time zone offset must be 1, 3, 5 or 6 characters')

        if tzstr[0:1] == b'-':
            mult = -1
        elif tzstr[0:1] == b'+':
            mult = 1
        else:
            raise ValueError('Time zone offset requires sign')

        hours = int(tzstr[1:3])
        if len(tzstr) == 3:
            minutes = 0
        else:
            minutes = int(tzstr[(4 if tzstr[3:4] == self._TIME_SEP else 3):])

        if zero_as_utc and hours == 0 and minutes == 0:
            return tz.tzutc()
        else:
            if minutes > 59:
                raise ValueError('Invalid minutes in time zone offset')

            if hours > 23:
                raise ValueError('Invalid hours in time zone offset')

            return tz.tzoffset(None, mult * (hours * 60 + minutes) * 60) 
Example #19
Source File: test.py    From registry-cli with GNU General Public License v3.0 5 votes vote down vote up
def test_get_non_utc_datetime_tags(self):
        self.registry.get_image_age.return_value = "2019-07-18T16:33:15.864962122+02:00"
        self.assertEqual(
            get_datetime_tags(self.registry, "imagename", ["latest"]),
            [{"tag": "latest", "datetime": datetime(2019, 7, 18, 16, 33, 15, 864962, tzinfo=tzoffset(None, 7200))}]
        ) 
Example #20
Source File: test_datetime_fields.py    From jsonmodels with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_time_field_parse_value():

    field = fields.TimeField()

    assert datetime.time() == field.parse_value('00:00:00')
    assert (
        datetime.time(2, 34, 45, tzinfo=tzoffset(None, 7200)) ==
        field.parse_value('2:34:45+02:00')
    )

    with pytest.raises(ValueError):
        field.parse_value('not a time') 
Example #21
Source File: MX.py    From electricitymap-contrib with MIT License 5 votes vote down vote up
def parse_date(date, hour):
    tzoffset = tz.tzoffset("CST", -3600 * 6)
    dt = datetime.datetime.strptime(date, "%d/%m/%Y")
    dt = dt.replace(hour=int(hour) - 1, tzinfo=tzoffset)
    return dt 
Example #22
Source File: test_timezones.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def test_timestamp_to_datetime_tzoffset(self):
        tzinfo = tzoffset(None, 7200)
        expected = Timestamp('3/11/2012 04:00', tz=tzinfo)
        result = Timestamp(expected.to_pydatetime())
        assert expected == result 
Example #23
Source File: test_timezones.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def test_dateutil_tzoffset_support(self):
        values = [188.5, 328.25]
        tzinfo = tzoffset(None, 7200)
        index = [datetime(2012, 5, 11, 11, tzinfo=tzinfo),
                 datetime(2012, 5, 11, 12, tzinfo=tzinfo)]
        series = Series(data=values, index=index)

        assert series.index.tz == tzinfo

        # it works! #2443
        repr(series.index[0]) 
Example #24
Source File: date_time.py    From yaql with Apache License 2.0 5 votes vote down vote up
def _get_tz(offset):
    if offset is None:
        return None
    if offset == ZERO_TIMESPAN:
        return UTCTZ
    return tz.tzoffset(None, seconds(offset)) 
Example #25
Source File: dates.py    From riko with MIT License 5 votes vote down vote up
def normalize_date(date):
    try:
        # See if date is a `time.struct_time`
        # if so, convert it and account for leapseconds
        tt, date = date, dt(*date[:5] + (min(date[5], 59),))
    except TypeError:
        pass
    else:
        is_dst = None if tt[8] is -1 else tt[8]

        try:
            tm_zone = tt.tm_zone
        except AttributeError:
            tm_zone = None
            tm_gmtoff = None
        else:
            tm_gmtoff = tt.tm_gmtoff

        if tm_zone:
            date = pytz.timezone(tm_zone).localize(date, is_dst=is_dst)
        elif tm_gmtoff:
            offset = tzoffset(None, tm_gmtoff)
            date.replace(tzinfo=offset)

    # Set timezone to UTC
    try:
        tzdate = date.astimezone(utc) if date.tzinfo else utc.localize(date)
    except AttributeError:
        tzdate = date

    return tzdate 
Example #26
Source File: isoparser.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def _parse_tzstr(self, tzstr, zero_as_utc=True):
        if tzstr == b'Z':
            return tz.tzutc()

        if len(tzstr) not in {3, 5, 6}:
            raise ValueError('Time zone offset must be 1, 3, 5 or 6 characters')

        if tzstr[0:1] == b'-':
            mult = -1
        elif tzstr[0:1] == b'+':
            mult = 1
        else:
            raise ValueError('Time zone offset requires sign')

        hours = int(tzstr[1:3])
        if len(tzstr) == 3:
            minutes = 0
        else:
            minutes = int(tzstr[(4 if tzstr[3:4] == self._TIME_SEP else 3):])

        if zero_as_utc and hours == 0 and minutes == 0:
            return tz.tzutc()
        else:
            if minutes > 59:
                raise ValueError('Invalid minutes in time zone offset')

            if hours > 23:
                raise ValueError('Invalid hours in time zone offset')

            return tz.tzoffset(None, mult * (hours * 60 + minutes) * 60) 
Example #27
Source File: isoparser.py    From pipenv with MIT License 5 votes vote down vote up
def _parse_tzstr(self, tzstr, zero_as_utc=True):
        if tzstr == b'Z' or tzstr == b'z':
            return tz.UTC

        if len(tzstr) not in {3, 5, 6}:
            raise ValueError('Time zone offset must be 1, 3, 5 or 6 characters')

        if tzstr[0:1] == b'-':
            mult = -1
        elif tzstr[0:1] == b'+':
            mult = 1
        else:
            raise ValueError('Time zone offset requires sign')

        hours = int(tzstr[1:3])
        if len(tzstr) == 3:
            minutes = 0
        else:
            minutes = int(tzstr[(4 if tzstr[3:4] == self._TIME_SEP else 3):])

        if zero_as_utc and hours == 0 and minutes == 0:
            return tz.UTC
        else:
            if minutes > 59:
                raise ValueError('Invalid minutes in time zone offset')

            if hours > 23:
                raise ValueError('Invalid hours in time zone offset')

            return tz.tzoffset(None, mult * (hours * 60 + minutes) * 60) 
Example #28
Source File: test_infofile.py    From barman with GNU General Public License v3.0 5 votes vote down vote up
def test_timezone_aware_parser(self):
        """
        Test the timezone_aware_parser method with different string
        formats
        """
        # test case 1 string with timezone info
        tz_string = '2009/05/13 19:19:30 -0400'
        result = load_datetime_tz(tz_string)
        assert result.tzinfo == tzoffset(None, -14400)

        # test case 2 string with timezone info with a different format
        tz_string = '2004-04-09T21:39:00-08:00'
        result = load_datetime_tz(tz_string)
        assert result.tzinfo == tzoffset(None, -28800)

        # test case 3 string without timezone info,
        # expecting tzlocal() as timezone
        tz_string = str(datetime.now())
        result = load_datetime_tz(tz_string)
        assert result.tzinfo == tzlocal()

        # test case 4 string with a wrong timezone format,
        # expecting tzlocal() as timezone
        tz_string = '16:08:12 05/08/03 AEST'
        with warnings.catch_warnings():
            warnings.filterwarnings(
                "ignore", message="tzname AEST identified but not understood.")
            result = load_datetime_tz(tz_string)
        assert result.tzinfo == tzlocal()


# noinspection PyMethodMayBeStatic 
Example #29
Source File: test_table_entity.py    From azure-cosmos-table-python with Apache License 2.0 5 votes vote down vote up
def test_timezone(self):
        # Arrange
        local_tz = tzoffset('BRST', -10800)
        local_date = datetime(2003, 9, 27, 9, 52, 43, tzinfo=local_tz)
        entity = self._create_random_base_entity_dict()
        entity.update({'date': local_date})

        # Act
        self.ts.insert_entity(self.table_name, entity)
        resp = self.ts.get_entity(self.table_name, entity['PartitionKey'], entity['RowKey'])

        # Assert
        self.assertIsNotNone(resp)
        self.assertEqual(resp.date, local_date.astimezone(tzutc()))
        self.assertEqual(resp.date.astimezone(local_tz), local_date) 
Example #30
Source File: twoplustwo.py    From poker with MIT License 5 votes vote down vote up
def _get_timezone(self, root):
        """Find timezone informatation on bottom of the page."""
        tz_str = root.xpath('//div[@class="smallfont" and @align="center"]')[0].text
        hours = int(self._tz_re.search(tz_str).group(1))
        return tzoffset(tz_str, hours * 60)