當前位置: 首頁>>代碼示例>>Python>>正文


Python datetime.now方法代碼示例

本文整理匯總了Python中datetime.now方法的典型用法代碼示例。如果您正苦於以下問題:Python datetime.now方法的具體用法?Python datetime.now怎麽用?Python datetime.now使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在datetime的用法示例。


在下文中一共展示了datetime.now方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: test_freezing_time_in_fixture

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import now [as 別名]
def test_freezing_time_in_fixture(testdir):
    testdir.makepyfile("""
        import pytest
        from datetime import date, datetime

        @pytest.fixture
        def today():
            return datetime.now().date()

        @pytest.mark.freeze_time('2017-05-20 15:42')
        def test_sth(today):
            assert today == date(2017, 5, 20)
    """)

    result = testdir.runpytest('-v', '-s')
    assert result.ret == 0 
開發者ID:ktosiek,項目名稱:pytest-freezegun,代碼行數:18,代碼來源:test_freezegun.py

示例2: test_class_just_fixture

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import now [as 別名]
def test_class_just_fixture(testdir):
    testdir.makepyfile("""
        from datetime import datetime
        import time

        class TestAsClass(object):

            def test_just_fixture(self, freezer):
                now = datetime.now()
                time.sleep(0.1)
                later = datetime.now()

                assert now == later
    """)

    result = testdir.runpytest('-v', '-s')
    assert result.ret == 0 
開發者ID:ktosiek,項目名稱:pytest-freezegun,代碼行數:19,代碼來源:test_freezegun.py

示例3: observe_inventory

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import now [as 別名]
def observe_inventory(owner, repo_name, pulls):
    for metric in ['additions', 'commits', 'deletions']:
        metric_sum = None
        if len(pulls) > 0:
            metric_sum = sum([getattr(p, metric) for p in pulls])
        else:
            metric_sum = 0

        logger.info(
            'Observed for owner "%s", repo "%s", %d %s' % (owner, repo_name, metric_sum, metric))

        CODE_INVENTORY.labels(owner, repo_name, metric).set(metric_sum)

    for pull in pulls:
        days_old = weekdays_between(pull.created_at, datetime.now())
        logger.info(
            'Observed for owner "%s", repo "%s", %.2f days old PR' % (owner, repo_name, days_old))
        CODE_INVENTORY_AGE.labels(owner, repo_name).observe(days_old) 
開發者ID:soundcloud,項目名稱:project-dev-kpis,代碼行數:20,代碼來源:inventory.py

示例4: test_load_dates_timezones

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import now [as 別名]
def test_load_dates_timezones():
    from dataflows import Flow, checkpoint
    from datetime import datetime, timezone
    import shutil

    dates = [
        datetime.now(),
        datetime.now(timezone.utc).astimezone()
    ]

    shutil.rmtree('.checkpoints/test_load_dates_timezones', ignore_errors=True)

    Flow(
        [{'date': d.date(), 'datetime': d} for d in dates],
        checkpoint('test_load_dates_timezones')
    ).process()

    results = Flow(
        checkpoint('test_load_dates_timezones')
    ).results()

    assert list(map(lambda x: x['date'], results[0][0])) == \
        list(map(lambda x: x.date(), dates))
    assert list(map(lambda x: x['datetime'], results[0][0])) == \
        list(map(lambda x: x, dates)) 
開發者ID:datahq,項目名稱:dataflows,代碼行數:27,代碼來源:test_lib.py

示例5: test_astimezone

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import now [as 別名]
def test_astimezone(self):
        # Pretty boring!  The TZ test is more interesting here.  astimezone()
        # simply can't be applied to a naive object.
        dt = self.theclass.now()
        f = FixedOffset(44, "")
        self.assertRaises(TypeError, dt.astimezone) # not enough args
        self.assertRaises(TypeError, dt.astimezone, f, f) # too many args
        self.assertRaises(TypeError, dt.astimezone, dt) # arg wrong type
        self.assertRaises(ValueError, dt.astimezone, f) # naive
        self.assertRaises(ValueError, dt.astimezone, tz=f)  # naive

        class Bogus(tzinfo):
            def utcoffset(self, dt): return None
            def dst(self, dt): return timedelta(0)
        bog = Bogus()
        self.assertRaises(ValueError, dt.astimezone, bog)   # naive

        class AlsoBogus(tzinfo):
            def utcoffset(self, dt): return timedelta(0)
            def dst(self, dt): return None
        alsobog = AlsoBogus()
        self.assertRaises(ValueError, dt.astimezone, alsobog) # also naive 
開發者ID:IronLanguages,項目名稱:ironpython2,代碼行數:24,代碼來源:test_datetime.py

示例6: latest_post_date

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import now [as 別名]
def latest_post_date(self):
        """
        Return the latest item's pubdate or updateddate. If no items
        have either of these attributes this return the current UTC date/time.
        """
        latest_date = None
        date_keys = ('updateddate', 'pubdate')

        for item in self.items:
            for date_key in date_keys:
                item_date = item.get(date_key)
                if item_date:
                    if latest_date is None or item_date > latest_date:
                        latest_date = item_date

        # datetime.now(tz=utc) is slower, as documented in django.utils.timezone.now
        return latest_date or datetime.datetime.utcnow().replace(tzinfo=utc) 
開發者ID:reBiocoder,項目名稱:bioforum,代碼行數:19,代碼來源:feedgenerator.py

示例7: describe

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import now [as 別名]
def describe(self, as_tuple=None, **kwargs):
        """
        This method is to retrieve test resources, method parameters are only used signature compatibility
        :param as_tuple: Set to true to return results as immutable named dictionaries instead of dictionaries
        :return: Test resource
        """

        def create_resource(r):
            return {
                actions.ops_automator_test_action.TEST_RESOURCE_ID: OpsautomatortestService.resource_id(r),
                "AwsAccount": self.aws_account,
                "Region": kwargs["region"] if "region" in kwargs else self.region,
                "Service": self.service_name,
                "ResourceTypeName": actions.ops_automator_test_action.TEST_RESOURCE_NAMES[0],
                "Tags": self.tags
            }

        start = datetime.now()

        self._args = kwargs
        result = [create_resource(i) for i in sorted(self._number_of_resources)]

        if self._args.get(actions.ops_automator_test_action.PARAM_TEST_SELECT_FAILING, False) in ["True", True]:
            raise Exception("Selection of resources fails")

        select_time = int(self._args.get(actions.ops_automator_test_action.PARAM_TEST_SELECT_DURATION, 0))

        if select_time != 0:
            variance = float(self._args.get(actions.ops_automator_test_action.PARAM_TEST_SELECT_DURATION_VARIANCE, 0))
            if variance != 0:
                select_time += (random.uniform(variance * -1, variance) * select_time)
            time_spend = (datetime.now() - start).total_seconds()
            if time_spend < select_time:
                time.sleep(select_time - time_spend)

        return result 
開發者ID:awslabs,項目名稱:aws-ops-automator,代碼行數:38,代碼來源:opsautomatortest_service.py

示例8: test_freezing_time

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import now [as 別名]
def test_freezing_time(testdir):
    testdir.makepyfile("""
        import pytest
        from datetime import date, datetime

        @pytest.mark.freeze_time('2017-05-20 15:42')
        def test_sth():
            assert datetime.now().date() == date(2017, 5, 20)
    """)

    result = testdir.runpytest('-v', '-s')
    assert result.ret == 0 
開發者ID:ktosiek,項目名稱:pytest-freezegun,代碼行數:14,代碼來源:test_freezegun.py

示例9: test_no_mark

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import now [as 別名]
def test_no_mark(testdir):
    testdir.makepyfile("""
        import datetime

        def test_sth():
            assert datetime.datetime.now() > {}
    """.format(repr(datetime.now())))

    result = testdir.runpytest('-v', '-s')
    assert result.ret == 0 
開發者ID:ktosiek,項目名稱:pytest-freezegun,代碼行數:12,代碼來源:test_freezegun.py

示例10: test_fixture_no_mark

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import now [as 別名]
def test_fixture_no_mark(testdir):
    testdir.makepyfile("""
        from datetime import datetime
        import time

        def test_just_fixture(freezer):
            now = datetime.now()
            time.sleep(0.1)
            later = datetime.now()

            assert now == later
    """)

    result = testdir.runpytest('-v', '-s')
    assert result.ret == 0 
開發者ID:ktosiek,項目名稱:pytest-freezegun,代碼行數:17,代碼來源:test_freezegun.py

示例11: test_fixture_freezes_time

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import now [as 別名]
def test_fixture_freezes_time(testdir):
    testdir.makepyfile("""
        import time

        def test_fixture_freezes_time(freezer):
            now = time.time()
            time.sleep(0.1)
            later = time.time()

            assert now == later
    """)

    result = testdir.runpytest('-v', '-s')
    assert result.ret == 0 
開發者ID:ktosiek,項目名稱:pytest-freezegun,代碼行數:16,代碼來源:test_freezegun.py

示例12: test_class_freezing_time

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import now [as 別名]
def test_class_freezing_time(testdir):
    testdir.makepyfile("""
        import pytest
        from datetime import date, datetime

        class TestAsClass(object):

            @pytest.mark.freeze_time('2017-05-20 15:42')
            def test_sth(self):
                assert datetime.now().date() == date(2017, 5, 20)
    """)

    result = testdir.runpytest('-v', '-s')
    assert result.ret == 0 
開發者ID:ktosiek,項目名稱:pytest-freezegun,代碼行數:16,代碼來源:test_freezegun.py

示例13: restart

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import now [as 別名]
def restart(self, timeout=None):
        """Restarts this Splunk instance.

        The service is unavailable until it has successfully restarted.

        If a *timeout* value is specified, ``restart`` blocks until the service
        resumes or the timeout period has been exceeded. Otherwise, ``restart`` returns
        immediately.

        :param timeout: A timeout period, in seconds.
        :type timeout: ``integer``
        """
        msg = { "value": "Restart requested by " + self.username + "via the Splunk SDK for Python"}
        # This message will be deleted once the server actually restarts.
        self.messages.create(name="restart_required", **msg)
        result = self.post("/services/server/control/restart")
        if timeout is None:
            return result
        start = datetime.now()
        diff = timedelta(seconds=timeout)
        while datetime.now() - start < diff:
            try:
                self.login()
                if not self.restart_required:
                    return result
            except Exception as e:
                sleep(1)
        raise Exception("Operation time out.") 
開發者ID:remg427,項目名稱:misp42splunk,代碼行數:30,代碼來源:client.py

示例14: search

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import now [as 別名]
def search(self, query, **kwargs):
        """Runs a search using a search query and any optional arguments you
        provide, and returns a `Job` object representing the search.

        :param query: A search query.
        :type query: ``string``
        :param kwargs: Arguments for the search (optional):

            * "output_mode" (``string``): Specifies the output format of the
              results.

            * "earliest_time" (``string``): Specifies the earliest time in the
              time range to
              search. The time string can be a UTC time (with fractional
              seconds), a relative time specifier (to now), or a formatted
              time string.

            * "latest_time" (``string``): Specifies the latest time in the time
              range to
              search. The time string can be a UTC time (with fractional
              seconds), a relative time specifier (to now), or a formatted
              time string.

            * "rf" (``string``): Specifies one or more fields to add to the
              search.

        :type kwargs: ``dict``
        :rtype: class:`Job`
        :returns: An object representing the created job.
        """
        return self.jobs.create(query, **kwargs) 
開發者ID:remg427,項目名稱:misp42splunk,代碼行數:33,代碼來源:client.py

示例15: touch

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import now [as 別名]
def touch(self):
        """Extends the expiration time of the search to the current time (now) plus
        the time-to-live (ttl) value.

        :return: The :class:`Job`.
        """
        self.post("control", action="touch")
        return self 
開發者ID:remg427,項目名稱:misp42splunk,代碼行數:10,代碼來源:client.py


注:本文中的datetime.now方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。