Python dateutil.tz.gettz() Examples

The following are 30 code examples of dateutil.tz.gettz(). 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: loop.py    From query-exporter with GNU General Public License v3.0 6 votes vote down vote up
def start(self):
        """Start timed queries execution."""
        for db in self._databases:
            try:
                await db.connect()
            except DataBaseError:
                self._increment_db_error_count(db)

        for query in self._timed_queries:
            if query.interval:
                call = PeriodicCall(self._run_query, query)
                call.start(query.interval)
            else:
                call = TimedCall(self._run_query, query)
                now = datetime.now().replace(tzinfo=gettz())
                cron_iter = croniter(query.schedule, now)

                def times_iter():
                    while True:
                        delta = next(cron_iter) - time.time()
                        yield self._loop.time() + delta

                call.start(times_iter())
            self._timed_calls[query.name] = call 
Example #2
Source File: util.py    From kotori with GNU Affero General Public License v3.0 6 votes vote down vote up
def parse_timestamp(timestamp):

    if isinstance(timestamp, text_type):

        # HACK: Assume CET (Europe/Berlin) for human readable timestamp w/o timezone offset
        qualified = any([token in timestamp for token in ['Z', '+', ' CET', ' CEST']])
        if not qualified:
            timestamp += ' CET'

        # Parse datetime string
        # Remark: Maybe use pandas.tseries.tools.parse_time_string?
        # TODO: Cache results of call to gettz to improve performance
        berlin = gettz('Europe/Berlin')
        tzinfos = {'CET': berlin, 'CEST': berlin}
        timestamp = parse(timestamp, tzinfos=tzinfos)

    return timestamp 
Example #3
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 #4
Source File: test_tz.py    From plugin.video.emby with GNU General Public License v3.0 6 votes vote down vote up
def __get_kiritimati_resolve_imaginary_test():
    # In the 2018d release of the IANA database, the Kiritimati "imaginary day"
    # data was corrected, so if the system zoneinfo is older than 2018d, the
    # Kiritimati test will fail.

    tzi = tz.gettz('Pacific/Kiritimati')
    new_version = False
    if not tz.datetime_exists(datetime(1995, 1, 1, 12, 30), tzi):
        zif = zoneinfo.get_zonefile_instance()
        if zif.metadata is not None:
            new_version = zif.metadata['tzversion'] >= '2018d'

        if new_version:
            tzi = zif.get('Pacific/Kiritimati')
    else:
        new_version = True

    if new_version:
        dates = (datetime(1994, 12, 31, 12, 30), datetime(1995, 1, 1, 12, 30))
    else:
        dates = (datetime(1995, 1, 1, 12, 30), datetime(1995, 1, 2, 12, 30))

    return (tzi, ) + dates 
Example #5
Source File: base.py    From alembic with MIT License 6 votes vote down vote up
def _generate_create_date(self):
        if self.timezone is not None:
            # First, assume correct capitalization
            tzinfo = tz.gettz(self.timezone)
            if tzinfo is None:
                # Fall back to uppercase
                tzinfo = tz.gettz(self.timezone.upper())
            if tzinfo is None:
                raise util.CommandError(
                    "Can't locate timezone: %s" % self.timezone
                )
            create_date = (
                datetime.datetime.utcnow()
                .replace(tzinfo=tz.tzutc())
                .astimezone(tzinfo)
            )
        else:
            create_date = datetime.datetime.now()
        return create_date 
Example #6
Source File: test_tz.py    From plugin.video.emby with GNU General Public License v3.0 6 votes vote down vote up
def testInZoneFoldEquality(self):
        # Two datetimes in the same zone are considered to be equal if their
        # wall times are equal, even if they have different absolute times.

        tzname = self._get_tzname('America/New_York')

        with self._gettz_context(tzname):
            NYC = self.gettz(tzname)
            UTC = tz.tzutc()

            dt0 = datetime(2011, 11, 6, 1, 30, tzinfo=NYC)
            dt1 = tz.enfold(dt0, fold=1)

            # Make sure these actually represent different times
            self.assertNotEqual(dt0.astimezone(UTC), dt1.astimezone(UTC))

            # Test that they compare equal
            self.assertEqual(dt0, dt1) 
Example #7
Source File: test_tz.py    From plugin.video.emby with GNU General Public License v3.0 6 votes vote down vote up
def testFoldLondon(self):
        tzname = self._get_tzname('Europe/London')

        with self._gettz_context(tzname):
            LON = self.gettz(tzname)
            UTC = tz.tzutc()

            t0_u = datetime(2013, 10, 27, 0, 30, tzinfo=UTC)   # BST
            t1_u = datetime(2013, 10, 27, 1, 30, tzinfo=UTC)   # GMT

            t0 = t0_u.astimezone(LON)
            t1 = t1_u.astimezone(LON)

            self.assertEqual(t0.replace(tzinfo=None),
                             datetime(2013, 10, 27, 1, 30))

            self.assertEqual(t1.replace(tzinfo=None),
                             datetime(2013, 10, 27, 1, 30))

            self.assertEqual(t0.utcoffset(), timedelta(hours=1))
            self.assertEqual(t1.utcoffset(), timedelta(hours=0)) 
Example #8
Source File: test_tz.py    From plugin.video.emby with GNU General Public License v3.0 6 votes vote down vote up
def testGapPositiveUTCOffset(self):
        # Test that we don't have a problem around gaps.
        tzname = self._get_tzname('Australia/Sydney')

        with self._gettz_context(tzname):
            SYD = self.gettz(tzname)

            t0_u = datetime(2012, 10, 6, 15, 30, tzinfo=tz.tzutc())  # AEST
            t1_u = datetime(2012, 10, 6, 16, 30, tzinfo=tz.tzutc())  # AEDT

            t0 = t0_u.astimezone(SYD)
            t1 = t1_u.astimezone(SYD)

            self.assertEqual(t0.replace(tzinfo=None),
                             datetime(2012, 10, 7, 1, 30))

            self.assertEqual(t1.replace(tzinfo=None),
                             datetime(2012, 10, 7, 3, 30))

            self.assertEqual(t0.utcoffset(), timedelta(hours=10))
            self.assertEqual(t1.utcoffset(), timedelta(hours=11)) 
Example #9
Source File: test_tz.py    From plugin.video.emby with GNU General Public License v3.0 6 votes vote down vote up
def testFoldPositiveUTCOffset(self):
        # Test that we can resolve ambiguous times
        tzname = self._get_tzname('Australia/Sydney')

        with self._gettz_context(tzname):
            SYD = self.gettz(tzname)

            t0_u = datetime(2012, 3, 31, 15, 30, tzinfo=tz.tzutc())  # AEST
            t1_u = datetime(2012, 3, 31, 16, 30, tzinfo=tz.tzutc())  # AEDT

            t0_syd0 = t0_u.astimezone(SYD)
            t1_syd1 = t1_u.astimezone(SYD)

            self.assertEqual(t0_syd0.replace(tzinfo=None),
                             datetime(2012, 4, 1, 2, 30))

            self.assertEqual(t1_syd1.replace(tzinfo=None),
                             datetime(2012, 4, 1, 2, 30))

            self.assertEqual(t0_syd0.utcoffset(), timedelta(hours=11))
            self.assertEqual(t1_syd1.utcoffset(), timedelta(hours=10)) 
Example #10
Source File: utils.py    From wechatpy with MIT License 6 votes vote down vote up
def timezone(zone):
    """Try to get timezone using pytz or python-dateutil

    :param zone: timezone str
    :return: timezone tzinfo or None
    """
    try:
        import pytz

        return pytz.timezone(zone)
    except ImportError:
        pass
    try:
        from dateutil.tz import gettz

        return gettz(zone)
    except ImportError:
        return None 
Example #11
Source File: test_tz.py    From plugin.video.emby with GNU General Public License v3.0 6 votes vote down vote up
def testFoldNegativeUTCOffset(self):
            # Test that we can resolve ambiguous times
            tzname = self._get_tzname('America/Toronto')

            with self._gettz_context(tzname):
                TOR = self.gettz(tzname)

                t0_u = datetime(2011, 11, 6, 5, 30, tzinfo=tz.tzutc())
                t1_u = datetime(2011, 11, 6, 6, 30, tzinfo=tz.tzutc())

                t0_tor = t0_u.astimezone(TOR)
                t1_tor = t1_u.astimezone(TOR)

                self.assertEqual(t0_tor.replace(tzinfo=None),
                                 datetime(2011, 11, 6, 1, 30))

                self.assertEqual(t1_tor.replace(tzinfo=None),
                                 datetime(2011, 11, 6, 1, 30))

                self.assertNotEqual(t0_tor.tzname(), t1_tor.tzname())
                self.assertEqual(t0_tor.utcoffset(), timedelta(hours=-4.0))
                self.assertEqual(t1_tor.utcoffset(), timedelta(hours=-5.0)) 
Example #12
Source File: test_parser.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def test_parse_tzinfos_fold():
    NYC = tz.gettz('America/New_York')
    tzinfos = {'EST': NYC, 'EDT': NYC}

    dt_exp = tz.enfold(datetime(2011, 11, 6, 1, 30, tzinfo=NYC), fold=1)
    dt = parse('2011-11-06T01:30 EST', tzinfos=tzinfos)

    assert dt == dt_exp
    assert dt.tzinfo is dt_exp.tzinfo
    assert getattr(dt, 'fold') == getattr(dt_exp, 'fold')
    assert dt.astimezone(tz.tzutc()) == dt_exp.astimezone(tz.tzutc()) 
Example #13
Source File: test_script_production.py    From alembic with MIT License 5 votes vote down vote up
def test_custom_tz_utc(self):
        self._test_tz(
            "utc",
            datetime.datetime(2012, 7, 25, 15, 8, 5),
            datetime.datetime(2012, 7, 25, 15, 8, 5, tzinfo=tz.gettz("UTC")),
        ) 
Example #14
Source File: test_script_production.py    From alembic with MIT License 5 votes vote down vote up
def test_custom_tz_lowercase(self):
        self._test_tz(
            "est5edt",
            datetime.datetime(2012, 7, 25, 15, 8, 5),
            datetime.datetime(
                2012, 7, 25, 11, 8, 5, tzinfo=tz.gettz("EST5EDT")
            ),
        ) 
Example #15
Source File: data_cleaner.py    From data-cleaner with MIT License 5 votes vote down vote up
def _parse_date(value, time_format):
        try:
            datetime = arrow.get(
                value, time_format,
                tzinfo=tz.gettz("America/Argentina/Buenos Aires"))
            date = datetime.isoformat().split("T")[0]

            if "D" in time_format:
                return date
            elif "M" in time_format:
                return "-".join(date.split("-")[:-1])
            else:
                return "-".join(date.split("-")[:-2])
        except:
            return "" 
Example #16
Source File: data_cleaner.py    From data-cleaner with MIT License 5 votes vote down vote up
def _parse_datetime(value, time_format):
        try:
            datetime = arrow.get(
                value, time_format,
                tzinfo=tz.gettz("America/Argentina/Buenos Aires"))
            print(value, time_format, datetime, "funciona")
            return datetime.isoformat()
        except:
            print(value, time_format, "no funciona")
            return "" 
Example #17
Source File: field.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def __init__(self, default_timezone=None, *args, **kwargs):
        """
        :arg default_timezone: timezone that will be automatically used for tz-naive values
            May be instance of `datetime.tzinfo` or string containing TZ offset
        """
        self._default_timezone = default_timezone
        if isinstance(self._default_timezone, string_types):
            self._default_timezone = tz.gettz(self._default_timezone)
        super(Date, self).__init__(*args, **kwargs) 
Example #18
Source File: profile.py    From quantified-self with MIT License 5 votes vote down vote up
def get_timezone(self):
        if self.location is None:
            return None
        if "TIMEZONE" not in self.location:
            return tz.tzlocal()

        return tz.gettz(self.location["TIMEZONE"]) 
Example #19
Source File: datetime.py    From yui with GNU Affero General Public License v3.0 5 votes vote down vote up
def datetime(*args, tzname: str = 'Asia/Seoul') -> dt.datetime:
    return dt.datetime(*args).replace(tzinfo=gettz(tzname)) 
Example #20
Source File: datetime.py    From yui with GNU Affero General Public License v3.0 5 votes vote down vote up
def now(tzname: str = 'Asia/Seoul') -> dt.datetime:
    """Helper to make current datetime."""

    return dt.datetime.now(gettz(tzname)) 
Example #21
Source File: test_tz.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def testInGapAware(self):
        tzi = tz.gettz('Australia/Sydney')

        dt = datetime(2012, 10, 7, 2, 30, tzinfo=tzi)

        self.assertFalse(tz.datetime_exists(dt)) 
Example #22
Source File: util.py    From project-dev-kpis with MIT License 5 votes vote down vote up
def to_utc(d):
    if d.tzinfo is not None and d.tzinfo.utcoffset(d) == timedelta(0):
        dutc = d
    elif d.tzinfo is None:
        dutc = local_tz.localize(d)
    else:
        dutc = d.astimezone(tz.gettz('UTC'))
    return dutc 
Example #23
Source File: test_datetime.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_loc_incremental_setitem_with_dst(self):
        # GH 20724
        base = datetime(2015, 11, 1, tzinfo=tz.gettz("US/Pacific"))
        idxs = [base + timedelta(seconds=i * 900) for i in range(16)]
        result = pd.Series([0], index=[idxs[0]])
        for ts in idxs:
            result.loc[ts] = 1
        expected = pd.Series(1, index=idxs)
        tm.assert_series_equal(result, expected) 
Example #24
Source File: test_imports.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def testZoneinfoStar(self):
        from dateutil.zoneinfo import gettz
        from dateutil.zoneinfo import gettz_db_metadata
        from dateutil.zoneinfo import rebuild

        zi_all = (gettz, gettz_db_metadata, rebuild)

        for var in zi_all:
            self.assertIsNot(var, None) 
Example #25
Source File: test_script_production.py    From alembic with MIT License 5 votes vote down vote up
def test_custom_tzdata_tz(self):
        self._test_tz(
            "Europe/Berlin",
            datetime.datetime(2012, 7, 25, 15, 8, 5),
            datetime.datetime(
                2012, 7, 25, 17, 8, 5, tzinfo=tz.gettz("Europe/Berlin")
            ),
        ) 
Example #26
Source File: test_tz.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def testKeivForward(self):
        tzi = tz.gettz('Europe/Kiev')
        dt = datetime(2018, 3, 25, 3, 30, tzinfo=tzi)
        dt_act = tz.resolve_imaginary(dt)
        dt_exp = datetime(2018, 3, 25, 4, 30, tzinfo=tzi)
        self.assertEqual(dt_act, dt_exp) 
Example #27
Source File: test_tz.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def testLondonForward(self):
        tzi = tz.gettz('Europe/London')
        dt = datetime(2018, 3, 25, 1, 30, tzinfo=tzi)
        dt_act = tz.resolve_imaginary(dt)
        dt_exp = datetime(2018, 3, 25, 2, 30, tzinfo=tzi)
        self.assertEqual(dt_act, dt_exp) 
Example #28
Source File: test_tz.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def testCanberraForward(self):
        tzi = tz.gettz('Australia/Canberra')
        dt = datetime(2018, 10, 7, 2, 30, tzinfo=tzi)
        dt_act = tz.resolve_imaginary(dt)
        dt_exp = datetime(2018, 10, 7, 3, 30, tzinfo=tzi)
        self.assertEqual(dt_act, dt_exp) 
Example #29
Source File: test_tz.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def testSpecifiedTzOverridesAttached(self):
        EST = tz.gettz('US/Eastern')
        AEST = tz.gettz('Australia/Sydney')

        dt = datetime(2012, 10, 7, 2, 30, tzinfo=EST)  # This time exists

        self.assertFalse(tz.datetime_exists(dt, tz=AEST)) 
Example #30
Source File: test_tz.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def testExistsNaive(self):
        tzi = tz.gettz('Australia/Sydney')

        dt = datetime(2012, 10, 7, 10, 30)

        self.assertTrue(tz.datetime_exists(dt, tz=tzi))