Python datetime.now() Examples

The following are 30 code examples for showing how to use datetime.now(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module datetime , or try the search function .

Example 1
Project: pytest-freezegun   Author: ktosiek   File: test_freezegun.py    License: MIT License 6 votes vote down vote up
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 
Example 2
Project: pytest-freezegun   Author: ktosiek   File: test_freezegun.py    License: MIT License 6 votes vote down vote up
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 
Example 3
Project: project-dev-kpis   Author: soundcloud   File: inventory.py    License: MIT License 6 votes vote down vote up
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) 
Example 4
Project: dataflows   Author: datahq   File: test_lib.py    License: MIT License 6 votes vote down vote up
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)) 
Example 5
Project: ironpython2   Author: IronLanguages   File: test_datetime.py    License: Apache License 2.0 6 votes vote down vote up
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 
Example 6
Project: bioforum   Author: reBiocoder   File: feedgenerator.py    License: MIT License 6 votes vote down vote up
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) 
Example 7
Project: BinderFilter   Author: dxwu   File: test_datetime.py    License: MIT License 6 votes vote down vote up
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 
Example 8
Project: aws-ops-automator   Author: awslabs   File: opsautomatortest_service.py    License: Apache License 2.0 5 votes vote down vote up
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 
Example 9
Project: pytest-freezegun   Author: ktosiek   File: test_freezegun.py    License: MIT License 5 votes vote down vote up
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 
Example 10
Project: pytest-freezegun   Author: ktosiek   File: test_freezegun.py    License: MIT License 5 votes vote down vote up
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 
Example 11
Project: pytest-freezegun   Author: ktosiek   File: test_freezegun.py    License: MIT License 5 votes vote down vote up
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 
Example 12
Project: pytest-freezegun   Author: ktosiek   File: test_freezegun.py    License: MIT License 5 votes vote down vote up
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 
Example 13
Project: pytest-freezegun   Author: ktosiek   File: test_freezegun.py    License: MIT License 5 votes vote down vote up
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 
Example 14
Project: misp42splunk   Author: remg427   File: client.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
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.") 
Example 15
Project: misp42splunk   Author: remg427   File: client.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
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) 
Example 16
Project: misp42splunk   Author: remg427   File: client.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
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 
Example 17
Project: misp42splunk   Author: remg427   File: client.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
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.") 
Example 18
Project: misp42splunk   Author: remg427   File: client.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
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) 
Example 19
Project: misp42splunk   Author: remg427   File: client.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
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 
Example 20
Project: misp42splunk   Author: remg427   File: client.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
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.") 
Example 21
Project: misp42splunk   Author: remg427   File: client.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
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) 
Example 22
Project: misp42splunk   Author: remg427   File: client.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
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 
Example 23
Project: misp42splunk   Author: remg427   File: client.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
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.") 
Example 24
Project: misp42splunk   Author: remg427   File: client.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
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) 
Example 25
Project: misp42splunk   Author: remg427   File: client.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
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 
Example 26
Project: misp42splunk   Author: remg427   File: client.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
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.") 
Example 27
Project: misp42splunk   Author: remg427   File: client.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
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) 
Example 28
Project: misp42splunk   Author: remg427   File: client.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
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 
Example 29
Project: d6tpipe   Author: d6t   File: pipe.py    License: MIT License 5 votes vote down vote up
def _tinydb_insert(db, filessync, filesremote, fileslocal):
    if db is not None:
        db.insert({'updated_at': datetime.now(), 'action': 'push', 'sync':filessync, 'remote':filesremote, 'local': fileslocal}) 
Example 30
Project: beavy   Author: beavyHQ   File: social_connection.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def from_profile(cls, user, profile):
        if not user or user.is_anonymous:
            if not app.config.get("SECURITY_REGISTERABLE"):
                msg = "User not found. Registration disabled."
                logging.warning(msg)
                raise Exception(_(msg))
            email = profile.data.get("email")
            if not email:
                msg = "Please provide an email address."
                logging.warning(msg)
                raise Exception(_(msg))
            conflict = User.query.filter(User.email == email).first()
            if conflict:
                msg = "Email {} is already used. Login and then connect " + \
                      "external profile."
                msg = _(msg).format(email)
                logging.warning(msg)
                raise Exception(msg)

            now = datetime.now()
            user = User(
                email=email,
                name="{} {}".format(profile.data.get("first_name"),
                                    profile.data.get("last_name")),
                confirmed_at=now,
                active=True)

            db.session.add(user)
            db.session.flush()

        assert user.id, "User does not have an id"
        connection = cls(user_id=user.id, **profile.data)
        db.session.add(connection)
        db.session.commit()
        return connection