Python dateutil.tz.tzlocal() Examples

The following are 30 code examples of dateutil.tz.tzlocal(). 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: dsub.py    From dsub with Apache License 2.0 6 votes vote down vote up
def _importance_of_task(task):
  """Tuple (importance, end-time). Smaller values are more important."""
  # The status of a job is going to be determined by the roll-up of its tasks.
  # A FAILURE or CANCELED task means the job has FAILED.
  # If none, then any RUNNING task, the job is still RUNNING.
  # If none, then the job status is SUCCESS.
  #
  # Thus the dominant task for each job is one that exemplifies its
  # status:
  #
  # 1- The first (FAILURE or CANCELED) task, or if none
  # 2- The first RUNNING task, or if none
  # 3- The first SUCCESS task.
  importance = {'FAILURE': 0, 'CANCELED': 0, 'RUNNING': 1, 'SUCCESS': 2}
  return (importance[task.get_field('task-status')],
          task.get_field(
              'end-time',
              dsub_util.replace_timezone(datetime.datetime.max, tzlocal()))) 
Example #2
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 #3
Source File: test_credentials.py    From aiobotocore with Apache License 2.0 6 votes vote down vote up
def test_envvarprovider_env_var_expiry():
    expiry_time = datetime.datetime.now(tzlocal()) - datetime.timedelta(hours=1)
    environ = {
        'AWS_ACCESS_KEY_ID': 'foo',
        'AWS_SECRET_ACCESS_KEY': 'bar',
        'AWS_CREDENTIAL_EXPIRATION': expiry_time.isoformat()
    }
    provider = credentials.AioEnvProvider(environ)
    creds = await provider.load()
    assert isinstance(creds, credentials.AioRefreshableCredentials)

    del environ['AWS_CREDENTIAL_EXPIRATION']

    with pytest.raises(botocore.exceptions.PartialCredentialsError):
        await creds.get_frozen_credentials()


# From class TestConfigFileProvider(BaseEnvVar): 
Example #4
Source File: __init__.py    From repokid with Apache License 2.0 6 votes vote down vote up
def apply(self, input_list):
        now = datetime.datetime.now(tzlocal())
        try:
            days_delta = self.config["minimum_age"]
        except KeyError:
            LOGGER.info("Minimum age not set in config, using default 90 days")
            days_delta = 90

        ago = datetime.timedelta(days=days_delta)

        too_young = []
        for role in input_list:
            if role.create_date > now - ago:
                LOGGER.info(
                    "Role {name} created too recently to cleanup. ({date})".format(
                        name=role.role_name, date=role.create_date
                    )
                )
                too_young.append(role)
        return too_young 
Example #5
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 #6
Source File: cli.py    From Watson with MIT License 6 votes vote down vote up
def convert(self, value, param, ctx):
        if value:
            date = self._parse_multiformat(value)
            if date is None:
                raise click.UsageError(
                    "Could not match value '{}' to any supported date format"
                    .format(value)
                )
            # When we parse a date, we want to parse it in the timezone
            # expected by the user, so that midnight is midnight in the local
            # timezone, not in UTC. Cf issue #16.
            date.tzinfo = tz.tzlocal()
            # Add an offset to match the week beginning specified in the
            # configuration
            if param.name == "week":
                week_start = ctx.obj.config.get(
                    "options", "week_start", "monday")
                date = apply_weekday_offset(
                    start_time=date, week_start=week_start)
            return date 
Example #7
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 #8
Source File: test_credentials.py    From aiobotocore with Apache License 2.0 6 votes vote down vote up
def refreshable_creds():
    def _f(mock_time_return_value=None, refresher_return_value='METADATA'):
        refresher = mock.AsyncMock()
        future_time = datetime.datetime.now(tzlocal()) + datetime.timedelta(hours=24)
        expiry_time = datetime.datetime.now(tzlocal()) - datetime.timedelta(minutes=30)
        metadata = {
            'access_key': 'NEW-ACCESS',
            'secret_key': 'NEW-SECRET',
            'token': 'NEW-TOKEN',
            'expiry_time': future_time.isoformat(),
            'role_name': 'rolename',
        }
        refresher.return_value = metadata if refresher_return_value == 'METADATA' \
            else refresher_return_value
        mock_time = mock.Mock()
        mock_time.return_value = mock_time_return_value
        creds = credentials.AioRefreshableCredentials(
            'ORIGINAL-ACCESS', 'ORIGINAL-SECRET', 'ORIGINAL-TOKEN',
            expiry_time, refresher, 'iam-role', time_fetcher=mock_time
        )
        return creds
    return _f 
Example #9
Source File: monitoringstats.py    From privacyidea with GNU Affero General Public License v3.0 6 votes vote down vote up
def write_stats(stats_key, stats_value, timestamp=None, reset_values=False):
    """
    Write a new statistics value to the database

    :param stats_key: The key, that identifies the measurement point
    :type stats_key: basestring
    :param stats_value: The value to be measured
    :type stats_value: int
    :param timestamp: The time, when the value was measured
    :type timestamp: timezone-aware datetime object
    :param reset_values: Whether old entries should be deleted
    :return: id of the database entry
    """
    timestamp = timestamp or datetime.datetime.now(tzlocal())
    monitoring_obj = _get_monitoring()
    monitoring_obj.add_value(stats_key, stats_value, timestamp, reset_values) 
Example #10
Source File: __init__.py    From privacyidea with GNU Affero General Public License v3.0 6 votes vote down vote up
def parse_legacy_time(ts, return_date=False):
    """
    The new timestrings are of the format YYYY-MM-DDThh:mm+oooo.
    They contain the timezone offset!
    
    Old legacy time strings are of format DD/MM/YY hh:mm without time zone 
    offset.
    
    This function parses string and returns the new formatted time string 
    including the timezone offset.
    :param timestring: 
    :param return_date: If set to True a date is returned instead of a string
    :return: 
    """
    from privacyidea.lib.tokenclass import DATE_FORMAT
    d = parse_date_string(ts)
    if not d.tzinfo:
        # we need to reparse the string
        d = parse_date_string(ts,
                              dayfirst=re.match("^\d\d[/\.]",ts)).replace(
                                  tzinfo=tzlocal())
    if return_date:
        return d
    else:
        return d.strftime(DATE_FORMAT) 
Example #11
Source File: source.py    From script.tvguide.fullscreen with GNU General Public License v2.0 6 votes vote down vote up
def local_time(self,ttime,year,month,day):
        match = re.search(r'(.{1,2}):(.{2}) ?(.{2})',ttime)
        if match:
            hour = int(match.group(1))
            minute = int(match.group(2))
            ampm = match.group(3)
            if ampm == "pm":
                if hour < 12:
                    hour = hour + 12
                    hour = hour % 24
            else:
                if hour == 12:
                    hour = 0

            london = timezone('Europe/Copenhagen')
            utc = timezone('UTC')
            utc_dt = datetime.datetime(int(year),int(month),int(day),hour,minute,0,tzinfo=utc)
            to_zone = tz.tzlocal()
            loc_dt = utc_dt.astimezone(to_zone)
            return loc_dt
            #ttime = "%02d:%02d" % (loc_dt.hour,loc_dt.minute)

        return ttime 
Example #12
Source File: tokenclass.py    From privacyidea with GNU Affero General Public License v3.0 6 votes vote down vote up
def set_next_pin_change(self, diff=None, password=False):
        """
        Sets the timestamp for the next_pin_change. Provide a
        difference like 90d (90 days).

        Either provider the
        :param diff: The time delta.
        :type diff: basestring
        :param password: Do no set next_pin_change but next_password_change
        :return: None
        """
        days = int(diff.lower().strip("d"))
        key = "next_pin_change"
        if password:
            key = "next_password_change"
        new_date = datetime.now(tzlocal()) + timedelta(days=days)
        self.add_tokeninfo(key, new_date.strftime(DATE_FORMAT)) 
Example #13
Source File: tokenclass.py    From privacyidea with GNU Affero General Public License v3.0 6 votes vote down vote up
def check_reset_failcount(self):
        """
        Checks if we should reset the failcounter due to the
        FAILCOUNTER_CLEAR_TIMEOUT

        :return: True, if the failcounter was resetted
        """
        timeout = 0
        try:
            timeout = int(get_from_config(FAILCOUNTER_CLEAR_TIMEOUT, 0))
        except Exception as exx:
            log.warning("Misconfiguration. Error retrieving "
                        "failcounter_clear_timeout: "
                        "{0!s}".format(exx))
        if timeout and self.token.failcount == self.get_max_failcount():
            now = datetime.now(tzlocal())
            lastfail = self.get_tokeninfo(FAILCOUNTER_EXCEEDED)
            if lastfail is not None:
                failcounter_exceeded = parse_legacy_time(lastfail, return_date=True)
                if now > failcounter_exceeded + timedelta(minutes=timeout):
                    self.reset()
                    return True
        return False 
Example #14
Source File: tokenclass.py    From privacyidea with GNU Affero General Public License v3.0 6 votes vote down vote up
def check_validity_period(self):
        """
        This checks if the datetime.now() is within the validity
        period of the token.

        :return: success
        :rtype: bool
        """
        start = self.get_validity_period_start()
        end = self.get_validity_period_end()

        if start:
            dt_start = parse_legacy_time(start, return_date=True)
            if dt_start > datetime.now(tzlocal()):
                return False

        if end:
            dt_end = parse_legacy_time(end, return_date=True)
            if dt_end < datetime.now(tzlocal()):
                return False

        return True 
Example #15
Source File: periodictask.py    From privacyidea with GNU Affero General Public License v3.0 6 votes vote down vote up
def calculate_next_timestamp(ptask, node, interval_tzinfo=None):
    """
    Calculate the timestamp of the next scheduled run of task ``ptask`` on node ``node``.
    We do not check if the task is even scheduled to run on the specified node.
    Malformed cron expressions may throw a ``ValueError``.

    The next timestamp is calculated based on the last time the task was run on the given node.
    If the task has never run on the node, the last update timestamp of the periodic tasks
    is used as a reference timestamp.

    :param ptask: Dictionary describing the periodic task, as from ``PeriodicTask.get()``
    :param node: Node on which the periodic task is scheduled
    :type node: unicode
    :param interval_tzinfo: Timezone in which the cron expression should be interpreted. Defaults to local time.
    :type interval_tzinfo: tzinfo
    :return: a timezone-aware (UTC) datetime object
    """
    if interval_tzinfo is None:
        interval_tzinfo = tzlocal()
    timestamp = ptask["last_runs"].get(node, ptask["last_update"])
    local_timestamp = timestamp.astimezone(interval_tzinfo)
    iterator = croniter(ptask["interval"], local_timestamp)
    next_timestamp = iterator.get_next(datetime)
    # This will again be a timezone-aware datetime, but we return a timezone-aware UTC timestamp
    return next_timestamp.astimezone(tzutc()) 
Example #16
Source File: test_lib_monitoringstats.py    From privacyidea with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_02_delete_stats(self):
        key1 = "otherkey"
        now = datetime.datetime.now(tzlocal())
        write_stats(key1, 12, timestamp=now- timedelta(days=1))
        write_stats(key1, 13, timestamp=now)
        write_stats(key1, 14, timestamp=now + timedelta(days=1))
        self.assertEqual(MonitoringStats.query.filter_by(stats_key=key1).count(), 3)

        # delete the last two entries
        r = delete_stats(key1, start_timestamp=now - timedelta(minutes=60))

        # check there is only one entry
        self.assertEqual(MonitoringStats.query.filter_by(stats_key=key1).count(), 1)
        self.assertEqual(r, 2)

        # Again write three entries
        write_stats(key1, 13, timestamp=now)
        write_stats(key1, 14, timestamp=now + timedelta(days=1))
        self.assertEqual(MonitoringStats.query.filter_by(stats_key=key1).count(), 3)

        # Delete the first two entries
        r = delete_stats(key1, end_timestamp=now + timedelta(minutes=60))
        self.assertEqual(MonitoringStats.query.filter_by(stats_key=key1).count(), 1)
        self.assertEqual(r, 2) 
Example #17
Source File: gcal.py    From pkmeter with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def update(self):
        self.data['events'] = []
        self.tzutc = tz.tzutc()
        self.tzlocal = tz.tzlocal()
        urls, colors = [], {}
        for cal in self._iter_calendars():
            urls.append(cal.url)
            colors[cal.url] = cal.color
        for result in utils.iter_responses(urls, timeout=5):
            response = result.get('response')
            if response:
                ical = Calendar.from_ical(response.read().decode('utf-8'))
                color = colors[result.get('url')]
                self.data['events'] += self._parse_events(ical, color)
        self.data['events'] = sorted(self.data['events'], key=lambda e:e['start'])
        # Calculate time to next event
        now = datetime.datetime.now()
        next = [e for e in self.data['events'] if e['start'] > now][0]['start'] if self.data['events'] else self.DELTANONE
        if next < now + datetime.timedelta(seconds=self.DEFAULT_INTERVAL*1.5): self.data['next'] = 'Now'
        else: self.data['next'] = utils.natural_time(next-now, 1)
        super(Plugin, self).update() 
Example #18
Source File: test_timezones.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def test_normalize_tz(self):
        rng = date_range('1/1/2000 9:30', periods=10, freq='D',
                         tz='US/Eastern')

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

        assert result.is_normalized
        assert not rng.is_normalized

        rng = date_range('1/1/2000 9:30', periods=10, freq='D', tz='UTC')

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

        assert result.is_normalized
        assert not rng.is_normalized

        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 
Example #19
Source File: test_astype.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def test_to_period_tz_dateutil(self):
        xp = date_range('1/1/2000', '4/1/2000').to_period()

        ts = date_range('1/1/2000', '4/1/2000', tz='dateutil/US/Eastern')

        result = ts.to_period()[0]
        expected = ts[0].to_period()

        assert result == expected
        tm.assert_index_equal(ts.to_period(), xp)

        ts = date_range('1/1/2000', '4/1/2000', tz=dateutil.tz.tzutc())

        result = ts.to_period()[0]
        expected = ts[0].to_period()

        assert result == expected
        tm.assert_index_equal(ts.to_period(), xp)

        ts = date_range('1/1/2000', '4/1/2000', tz=tzlocal())

        result = ts.to_period()[0]
        expected = ts[0].to_period()

        assert result == expected
        tm.assert_index_equal(ts.to_period(), xp) 
Example #20
Source File: test_astype.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def test_to_period_tz_explicit_pytz(self):
        xp = date_range('1/1/2000', '4/1/2000').to_period()

        ts = date_range('1/1/2000', '4/1/2000', tz=pytz.timezone('US/Eastern'))

        result = ts.to_period()[0]
        expected = ts[0].to_period()

        assert result == expected
        tm.assert_index_equal(ts.to_period(), xp)

        ts = date_range('1/1/2000', '4/1/2000', tz=pytz.utc)

        result = ts.to_period()[0]
        expected = ts[0].to_period()

        assert result == expected
        tm.assert_index_equal(ts.to_period(), xp)

        ts = date_range('1/1/2000', '4/1/2000', tz=tzlocal())

        result = ts.to_period()[0]
        expected = ts[0].to_period()

        assert result == expected
        tm.assert_index_equal(ts.to_period(), xp) 
Example #21
Source File: test_timezones.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def test_dti_to_pydatetime(self):
        dt = dateutil.parser.parse('2012-06-13T01:39:00Z')
        dt = dt.replace(tzinfo=tzlocal())

        arr = np.array([dt], dtype=object)

        result = to_datetime(arr, utc=True)
        assert result.tz is pytz.utc

        rng = date_range('2012-11-03 03:00', '2012-11-05 03:00', tz=tzlocal())
        arr = rng.to_pydatetime()
        result = to_datetime(arr, utc=True)
        assert result.tz is pytz.utc 
Example #22
Source File: runner.py    From probe-scraper with Mozilla Public License 2.0 5 votes vote down vote up
def general_data():
    return {
        "lastUpdate": datetime.datetime.now(tzlocal()).isoformat(),
    } 
Example #23
Source File: test_credentials.py    From aiobotocore with Apache License 2.0 5 votes vote down vote up
def test_instancemetadata_load():
    timeobj = datetime.datetime.now(tzlocal())
    timestamp = (timeobj + datetime.timedelta(hours=24)).isoformat()

    fetcher = mock.AsyncMock()
    fetcher.retrieve_iam_role_credentials.return_value = {
        'access_key': 'a',
        'secret_key': 'b',
        'token': 'c',
        'expiry_time': timestamp,
        'role_name': 'myrole',
    }

    provider = credentials.AioInstanceMetadataProvider(
        iam_role_fetcher=fetcher
    )
    creds = await provider.load()
    assert creds is not None
    assert creds.method == 'iam-role'

    creds = await creds.get_frozen_credentials()
    assert creds.access_key == 'a'
    assert creds.secret_key == 'b'
    assert creds.token == 'c'


# From class CredentialResolverTest(BaseEnvVar): 
Example #24
Source File: test_credentials.py    From aiobotocore with Apache License 2.0 5 votes vote down vote up
def test_assumerolefetcher_cache_in_cache_but_expired():
    response = {
        'Credentials': {
            'AccessKeyId': 'foo',
            'SecretAccessKey': 'bar',
            'SessionToken': 'baz',
            'Expiration': some_future_time().isoformat(),
        },
    }
    client_creator = assume_role_client_creator(response)
    cache = {
        'development--myrole': {
            'Credentials': {
                'AccessKeyId': 'foo-cached',
                'SecretAccessKey': 'bar-cached',
                'SessionToken': 'baz-cached',
                'Expiration': datetime.datetime.now(tzlocal()),
            }
        }
    }

    refresher = credentials.AioAssumeRoleCredentialFetcher(
        client_creator,
        credentials.AioCredentials('a', 'b', 'c'),
        'myrole',
        cache=cache
    )
    expected = get_expected_creds_from_response(response)
    response = await refresher.fetch_credentials()

    assert response == expected 
Example #25
Source File: test_credentials.py    From aiobotocore with Apache License 2.0 5 votes vote down vote up
def some_future_time():
    timeobj = datetime.datetime.now(tzlocal())
    return timeobj + datetime.timedelta(hours=24) 
Example #26
Source File: test_credentials.py    From aiobotocore with Apache License 2.0 5 votes vote down vote up
def test_refreshablecredentials_refresh_returns_partial(refreshable_creds):
    creds = refreshable_creds(
        mock_time_return_value=datetime.datetime.now(tzlocal()),
        refresher_return_value={'access_key': 'akid'}
    )

    assert creds.refresh_needed()

    with pytest.raises(botocore.exceptions.CredentialRetrievalError):
        await creds.get_frozen_credentials()


# From class TestDeferredRefreshableCredentials(unittest.TestCase): 
Example #27
Source File: test_credentials.py    From aiobotocore with Apache License 2.0 5 votes vote down vote up
def test_refreshablecredentials_refresh_returns_none(refreshable_creds):
    creds = refreshable_creds(
        mock_time_return_value=datetime.datetime.now(tzlocal()),
        refresher_return_value=None
    )

    assert creds.refresh_needed()

    with pytest.raises(botocore.exceptions.CredentialRetrievalError):
        await creds.get_frozen_credentials() 
Example #28
Source File: test_credentials.py    From aiobotocore with Apache License 2.0 5 votes vote down vote up
def test_refreshablecredentials_refresh_returns_empty_dict(refreshable_creds):
    creds = refreshable_creds(
        mock_time_return_value=datetime.datetime.now(tzlocal()),
        refresher_return_value={}
    )

    assert creds.refresh_needed()

    with pytest.raises(botocore.exceptions.CredentialRetrievalError):
        await creds.get_frozen_credentials() 
Example #29
Source File: test_credentials.py    From aiobotocore with Apache License 2.0 5 votes vote down vote up
def test_refreshablecredentials_get_credentials_set(refreshable_creds):
    creds = refreshable_creds(
        mock_time_return_value=(datetime.datetime.now(tzlocal()) -
                                datetime.timedelta(minutes=60))
    )

    assert not creds.refresh_needed()

    credentials_set = await creds.get_frozen_credentials()
    assert isinstance(credentials_set, credentials.ReadOnlyCredentials)
    assert credentials_set.access_key == 'ORIGINAL-ACCESS'
    assert credentials_set.secret_key == 'ORIGINAL-SECRET'
    assert credentials_set.token == 'ORIGINAL-TOKEN' 
Example #30
Source File: local.py    From dsub with Apache License 2.0 5 votes vote down vote up
def _get_events_from_task_dir(self, task_dir):
    try:
      with open(os.path.join(task_dir, 'events.txt'), 'r') as f:
        events = []
        for line in f:
          if line.rstrip():
            name, time_string = line.split(',')
            start_time = dsub_util.replace_timezone(
                datetime.datetime.strptime(time_string.rstrip(),
                                           '%Y-%m-%d %H:%M:%S.%f'), tzlocal())
            events.append({'name': name, 'start-time': start_time})
        return events
    except (IOError, OSError):
      return None