当前位置: 首页>>代码示例>>Python>>正文


Python datetime.min方法代码示例

本文整理汇总了Python中datetime.datetime.min方法的典型用法代码示例。如果您正苦于以下问题:Python datetime.min方法的具体用法?Python datetime.min怎么用?Python datetime.min使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在datetime.datetime的用法示例。


在下文中一共展示了datetime.min方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: select_within_time

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import min [as 别名]
def select_within_time(self, start_time=None, end_time=None, as_db=False):
        """
        Selects records within a specific time
        :param start_time:
            Earliest time as instance of :class: datetime.datetime
        :param end_time:
            Latest time as instance of :class: datetime.datetime
        """
        if start_time:
            assert isinstance(start_time, datetime)
        else:
            start_time = datetime.min

        if end_time:
            assert isinstance(end_time, datetime)
        else:
            end_time = datetime.now()
        idx = []
        for iloc, record in enumerate(self.database.records):
            if (record.event.datetime >= start_time) and\
                (record.event.datetime <= end_time):
                idx.append(iloc)
        return self.select_records(idx, as_db) 
开发者ID:GEMScienceTools,项目名称:gmpe-smtk,代码行数:25,代码来源:strong_motion_selector.py

示例2: time_coverage

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import min [as 别名]
def time_coverage(self, value):
        if self.single_file:
            if value is None:
                # The default for single file filesets:
                self._time_coverage = [
                    datetime.min,
                    datetime.max
                ]
            else:
                self._time_coverage = [
                    to_datetime(value[0]),
                    to_datetime(value[1]),
                ]
        elif value is not None:
            self._time_coverage = to_timedelta(value)
        else:
            self._time_coverage = None

        # Reset the info cache because some file information may have changed
        # now
        self.info_cache = {} 
开发者ID:atmtools,项目名称:typhon,代码行数:23,代码来源:fileset.py

示例3: can_merge

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import min [as 别名]
def can_merge(self, other):
        """Check if two alerts can be merged together.

        Args:
            other (Alert): Check if the instance can merge with this other alert.

        Returns:
            True if these alerts fit in the same merge window and have the same merge key values.
        """
        if not self.merge_enabled or not other.merge_enabled:
            # Merge information is not defined for both of these alerts.
            return False

        older, newer = min(self, other), max(self, other)
        if newer.created > older.created + older.merge_window:
            # These alerts won't fit in a single merge window.
            return False

        if set(self.merge_by_keys) != set(other.merge_by_keys):
            # These alerts have different definitions of merge keys.
            return False

        return all(utils.get_first_key(self.record, key) == utils.get_first_key(other.record, key)
                   for key in self.merge_by_keys) 
开发者ID:airbnb,项目名称:streamalert,代码行数:26,代码来源:alert.py

示例4: test_kill_timed_out_processors_kill

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import min [as 别名]
def test_kill_timed_out_processors_kill(self, mock_kill, mock_pid):
        mock_pid.return_value = 1234
        manager = DagFileProcessorManager(
            dag_directory='directory',
            max_runs=1,
            processor_factory=MagicMock().return_value,
            processor_timeout=timedelta(seconds=5),
            signal_conn=MagicMock(),
            dag_ids=[],
            pickle_dags=False,
            async_mode=True)

        processor = DagFileProcessorProcess('abc.txt', False, [], [])
        processor._start_time = timezone.make_aware(datetime.min)
        manager._processors = {'abc.txt': processor}
        manager._kill_timed_out_processors()
        mock_kill.assert_called_once_with() 
开发者ID:apache,项目名称:airflow,代码行数:19,代码来源:test_dag_processing.py

示例5: _get_sms_providers_for_update

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import min [as 别名]
def _get_sms_providers_for_update(time_threshold):
    """
    Returns a list of providers, while holding a for_update lock on the provider details table, guaranteeing that those
    providers won't change (but can still be read) until you've committed/rolled back your current transaction.

    if any of the providers have been changed recently, it returns an empty list - it's still your responsiblity to
    release the transaction in that case
    """
    # get current priority of both providers
    q = ProviderDetails.query.filter(
        ProviderDetails.notification_type == 'sms',
        ProviderDetails.active
    ).with_for_update().all()

    # if something updated recently, don't update again. If the updated_at is null, treat it as min time
    if any((provider.updated_at or datetime.min) > datetime.utcnow() - time_threshold for provider in q):
        current_app.logger.info(f"Not adjusting providers, providers updated less than {time_threshold} ago.")
        return []

    return q 
开发者ID:alphagov,项目名称:notifications-api,代码行数:22,代码来源:provider_details_dao.py

示例6: dao_reduce_sms_provider_priority

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import min [as 别名]
def dao_reduce_sms_provider_priority(identifier, *, time_threshold):
    """
    Will reduce a chosen sms provider's priority, and increase the other provider's priority by 10 points each.
    If either provider has been updated in the last `time_threshold`, then it won't take any action.
    """
    amount_to_reduce_by = 10
    providers_list = _get_sms_providers_for_update(time_threshold)

    if not providers_list:
        return

    providers = {provider.identifier: provider for provider in providers_list}
    other_identifier = get_alternative_sms_provider(identifier)

    reduced_provider = providers[identifier]
    increased_provider = providers[other_identifier]

    # always keep values between 0 and 100
    reduced_provider_priority = max(0, reduced_provider.priority - amount_to_reduce_by)
    increased_provider_priority = min(100, increased_provider.priority + amount_to_reduce_by)

    _adjust_provider_priority(reduced_provider, reduced_provider_priority)
    _adjust_provider_priority(increased_provider, increased_provider_priority) 
开发者ID:alphagov,项目名称:notifications-api,代码行数:25,代码来源:provider_details_dao.py

示例7: dao_adjust_provider_priority_back_to_resting_points

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import min [as 别名]
def dao_adjust_provider_priority_back_to_resting_points():
    """
    Provided that neither SMS provider has been modified in the last hour, move both providers by 10 percentage points
    each towards their defined resting points (set in SMS_PROVIDER_RESTING_POINTS in config.py).
    """
    amount_to_reduce_by = 10
    time_threshold = timedelta(hours=1)

    providers = _get_sms_providers_for_update(time_threshold)

    for provider in providers:
        target = current_app.config['SMS_PROVIDER_RESTING_POINTS'][provider.identifier]
        current = provider.priority

        if current != target:
            if current > target:
                new_priority = max(target, provider.priority - amount_to_reduce_by)
            else:
                new_priority = min(target, provider.priority + amount_to_reduce_by)

            _adjust_provider_priority(provider, new_priority) 
开发者ID:alphagov,项目名称:notifications-api,代码行数:23,代码来源:provider_details_dao.py

示例8: test_adjust_provider_priority_adds_history

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import min [as 别名]
def test_adjust_provider_priority_adds_history(
    restore_provider_details,
    notify_user,
    mmg_provider,
):
    # need to update these manually to avoid triggering the `onupdate` clause of the updated_at column
    ProviderDetails.query.filter(ProviderDetails.identifier == 'mmg').update({'updated_at': datetime.min})

    old_provider_history_rows = ProviderDetailsHistory.query.filter(
        ProviderDetailsHistory.id == mmg_provider.id
    ).order_by(
        desc(ProviderDetailsHistory.version)
    ).all()

    _adjust_provider_priority(mmg_provider, 50)

    updated_provider_history_rows = ProviderDetailsHistory.query.filter(
        ProviderDetailsHistory.id == mmg_provider.id
    ).order_by(
        desc(ProviderDetailsHistory.version)
    ).all()

    assert len(updated_provider_history_rows) - len(old_provider_history_rows) == 1
    assert updated_provider_history_rows[0].version - old_provider_history_rows[0].version == 1
    assert updated_provider_history_rows[0].priority == 50 
开发者ID:alphagov,项目名称:notifications-api,代码行数:27,代码来源:test_provider_details_dao.py

示例9: start

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import min [as 别名]
def start(self, data):
        # write down the 'reset when' value
        if not isinstance(self.p.when, integer_types):  # expect time/datetime
            self._rstwhen = self.p.when
            self._tzdata = self.p.tzdata
        else:
            self._tzdata = data if self.p.tzdata is None else self.p.tzdata

            if self.p.when == SESSION_START:
                self._rstwhen = self._tzdata.p.sessionstart
            elif self.p.when == SESSION_END:
                self._rstwhen = self._tzdata.p.sessionend

        self._isdata = isinstance(self._tzdata, AbstractDataBase)
        self._reset_when()

        self._nexteos = datetime.min
        self._curdate = date.min

        self._curmonth = -1  # non-existent month
        self._monthmask = collections.deque()

        self._curweek = -1  # non-existent week
        self._weekmask = collections.deque() 
开发者ID:mementum,项目名称:backtrader,代码行数:26,代码来源:timer.py

示例10: test_raises_exception_timeout

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import min [as 别名]
def test_raises_exception_timeout(self):
        task = create_task(
            SetOrgWideDefaults,
            {
                "managed": True,
                "api_version": "47.0",
                "api_names": "bar,foo",
                "org_wide_defaults": [
                    {
                        "api_name": "Account",
                        "internal_sharing_model": "Private",
                        "external_sharing_model": "Private",
                    }
                ],
            },
        )

        task.time_start = datetime.min
        with pytest.raises(CumulusCIException):
            task._poll_action() 
开发者ID:SFDO-Tooling,项目名称:CumulusCI,代码行数:22,代码来源:test_sharing.py

示例11: _call_with_throttling_per_method

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import min [as 别名]
def _call_with_throttling_per_method(self, method_name, *args, **kwargs):
        api_struct = self._pick_api_with_shortest_waiting_time_for_method(method_name)
        now = datetime.now()
        throttle_time = api_struct[1].get(method_name, datetime.min)
        time_since_throttle = (now - throttle_time).seconds
        to_wait = self.time_to_wait - time_since_throttle + 1

        if to_wait > 0:
            logger.debug("<{1}>: Rate limits exhausted, waiting {0} seconds".format(
                to_wait, now.strftime('%H:%M:%S')))
            time.sleep(to_wait)

        try:
            return api_struct[0].__getattribute__(method_name)(*args, **kwargs)
        except TweepError as e:
            error_dict = parse_tweepy_error(e)
            if error_dict["code"] in [RATE_LIMIT_ERROR, TOO_MANY_REQUESTS, OVER_CAP_ERROR]:
                api_struct[1][method_name] = now
                logger.debug("Received limit message: {0}".format(error_dict["message"]))
                return self._call_with_throttling_per_method(method_name, *args, **kwargs)
            else:
                raise(e) 
开发者ID:SMAPPNYU,项目名称:smappPy,代码行数:24,代码来源:tweepy_pool.py

示例12: test_with_1_api_in_pool_sets_throttle_time_if_rate_limit_error

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import min [as 别名]
def test_with_1_api_in_pool_sets_throttle_time_if_rate_limit_error():
    """
    If the tweepy.API throws a rate-limit error, it should note the time of that error
    in apis[x][1].
    """
    api_mock = MagicMock(spec=tweepy.API)
    api_mock.return_value = api_mock
    ut_mock = Mock(return_value=0)
    api_mock.user_timeline = ut_mock

    api_mock.user_timeline.side_effect = raise_error_once()

    with patch('tweepy.API', api_mock):
        with patch('time.sleep'):
            api_pool = tweepy_pool.APIPool([OAUTH_DICT])
            api_pool.user_timeline(user_id=234)
    api_mock.user_timeline.assert_called_with(user_id=234)
    ok_(api_pool._apis[0][1]['user_timeline'] > datetime.min) 
开发者ID:SMAPPNYU,项目名称:smappPy,代码行数:20,代码来源:tweepy_pool_tests.py

示例13: __init__

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import min [as 别名]
def __init__(self, client, id, json={}):
        self._set('_populated', False)
        self._set('_last_updated', datetime.min)
        self._set('_client', client)

        #: self._raw_json is a copy of the json received from the API on population,
        #: and cannot be relied upon to be current.  Local changes to mutable fields
        #: that have not been saved will not be present, and volatile fields will not
        #: be updated on access.
        self._set('_raw_json', None)

        for prop in type(self).properties:
            self._set(prop, None)

        self._set('id', id)
        if hasattr(type(self), 'id_attribute'):
            self._set(getattr(type(self), 'id_attribute'), id)

        self._populate(json) 
开发者ID:linode,项目名称:linode_api4-python,代码行数:21,代码来源:base.py

示例14: get_course_assessment

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import min [as 别名]
def get_course_assessment(course_names, cutoff=None, assessment_url=None):
    """
    Returns all the course assessment for the given
    courses that occur after the given cutoff.
    """
    if assessment_url is None:
        joined_assessment_url = get_course_assessment_page(course_names)
    else:
        joined_assessment_url = assessment_url
        http_response = get_uq_request(joined_assessment_url)
    if http_response.status_code != requests.codes.ok:
        raise HttpException(joined_assessment_url, http_response.status_code)
    html = BeautifulSoup(http_response.content, 'html.parser')
    assessment_table = html.find('table', class_='tblborder')
    # Start from 1st index to skip over the row containing column names.
    assessment = assessment_table.findAll('tr')[1:]
    parsed_assessment = map(get_parsed_assessment_item, assessment)
    # If no cutoff is specified, set cutoff to UNIX epoch (i.e. filter nothing).
    cutoff = cutoff or datetime.min
    assessment_filter = partial(is_assessment_after_cutoff, cutoff=cutoff)
    filtered_assessment = filter(assessment_filter, parsed_assessment)
    return list(filtered_assessment) 
开发者ID:UQComputingSociety,项目名称:uqcsbot,代码行数:24,代码来源:uq_course_utils.py

示例15: need_update

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import min [as 别名]
def need_update() -> bool:
    """
    Cheks if cache needs update based on cache file modification date.

    Returns:
        True if the cache file is older than sync interval in hours.
    """
    vms_cache_filename = get_cache_path()
    modified = datetime.min
    if isfile(vms_cache_filename):
        modified = datetime.fromtimestamp(getmtime(vms_cache_filename))

    if modified < datetime.now() - timedelta(hours=int(sync_interval)):
        return True

    return False 
开发者ID:avanzzzi,项目名称:hypy,代码行数:18,代码来源:cache.py


注:本文中的datetime.datetime.min方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。