Python datetime.now() Examples

The following are code examples for showing how to use datetime.now(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.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 2
Project: adh6   Author: bonnetn   File: test_member_manager.py    GNU General Public License v3.0 6 votes vote down vote up
def test_happy_path_without_start_time(self, ctx,
                                           mock_membership_repository: MagicMock,
                                           mock_member_repository: MagicMock,
                                           member_manager: MemberManager):
        # Given that now == TEST_DATE (monkey patch datetime.now())
        # See here: http://blog.xelnor.net/python-mocking-datetime/
        with mock.patch.object(datetime, 'datetime', mock.Mock(wraps=datetime.datetime)) as patched:
            patched.now.return_value = TEST_DATE1

            # When...
            member_manager.new_membership(ctx, TEST_USERNAME, 1, 'card')

        # Expect...
        expected_start_date = TEST_DATE1
        expected_end_date = TEST_DATE1 + datetime.timedelta(days=1)

        # Expect to create a new membership record...
        self._assert_membership_record_was_created(ctx, TEST_USERNAME, mock_membership_repository,
                                                   expected_start_date, expected_end_date)

        # And update the member object.
        mock_member_repository.update_member.assert_called_once_with(ctx, TEST_USERNAME,
                                                                     departure_date=expected_end_date.isoformat()) 
Example 3
Project: pytest-freezegun   Author: ktosiek   File: test_freezegun.py    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 4
Project: project-dev-kpis   Author: soundcloud   File: inventory.py    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 5
Project: atlas   Author: Kayra   File: views.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def skillListView(request):

    try:
        List.objects.get(date=datetime.now())
        tasks = ListTask.objects.filter(list__date=datetime.now()).order_by('position')

    except List.DoesNotExist:

        try:
            createList(request.user)
            tasks = ListTask.objects.filter(list__date=datetime.now(), list__user=request.user).order_by('position')
        except (Days.DoesNotExist, Task.DoesNotExist, Skill.DoesNotExist):
            return redirect('skills:setup')

    return render(request, 'skills/skill_list.html', {
        'list': tasks,
    })


# API ######################################################################### 
Example 6
Project: voicebot   Author: JustinaPetr   File: actions.py    GNU General Public License v3.0 6 votes vote down vote up
def run(self, dispatcher, tracker, domain):
        import datetime
        budget = tracker.get_slot('budget')
        company = tracker.get_slot('company_name')
        email = tracker.get_slot('email')
        jobfunction = tracker.get_slot('job_function')
        name = tracker.get_slot('person_name')
        use_case = tracker.get_slot('use_case')
        date = datetime.datetime.now().strftime("%d/%m/%Y")

        sales_info = [company, use_case, budget, date, name, jobfunction,
                      email]

        gdrive = GDriveService()
        try:
            gdrive.store_data(sales_info)
            return [SlotSet('data_stored', True)]
        except Exception as e:
            logger.error("Failed to write data to gdocs. Error: {}"
                         "".format(e.message), exc_info=True)
            return [SlotSet('data_stored', False)] 
Example 7
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_subclass_must_override(self):
        class NotEnough(tzinfo):
            def __init__(self, offset, name):
                self.__offset = offset
                self.__name = name
        self.assertTrue(issubclass(NotEnough, tzinfo))
        ne = NotEnough(3, "NotByALongShot")
        self.assertIsInstance(ne, tzinfo)

        dt = datetime.now()
        self.assertRaises(NotImplementedError, ne.tzname, dt)
        self.assertRaises(NotImplementedError, ne.utcoffset, dt)
        self.assertRaises(NotImplementedError, ne.dst, dt) 
Example 8
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_normal(self):
        fo = FixedOffset(3, "Three")
        self.assertIsInstance(fo, tzinfo)
        for dt in datetime.now(), None:
            self.assertEqual(fo.utcoffset(dt), timedelta(minutes=3))
            self.assertEqual(fo.tzname(dt), "Three")
            self.assertEqual(fo.dst(dt), timedelta(minutes=42)) 
Example 9
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_roundtrip(self):
        for dt in (self.theclass(1, 2, 3, 4, 5, 6, 7),
                   self.theclass.now()):
            # Verify dt -> string -> datetime identity.
            s = repr(dt)
            self.assertTrue(s.startswith('datetime.'))
            s = s[9:]
            dt2 = eval(s)
            self.assertEqual(dt, dt2)

            # Verify identity via reconstructing from pieces.
            dt2 = self.theclass(dt.year, dt.month, dt.day,
                                dt.hour, dt.minute, dt.second,
                                dt.microsecond)
            self.assertEqual(dt, dt2) 
Example 10
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_more_astimezone(self):
        # The inherited test_astimezone covered some trivial and error cases.
        fnone = FixedOffset(None, "None")
        f44m = FixedOffset(44, "44")
        fm5h = FixedOffset(-timedelta(hours=5), "m300")

        dt = self.theclass.now(tz=f44m)
        self.assertIs(dt.tzinfo, f44m)
        # Replacing with degenerate tzinfo raises an exception.
        self.assertRaises(ValueError, dt.astimezone, fnone)
        # Ditto with None tz.
        self.assertRaises(TypeError, dt.astimezone, None)
        # Replacing with same tzinfo makes no change.
        x = dt.astimezone(dt.tzinfo)
        self.assertIs(x.tzinfo, f44m)
        self.assertEqual(x.date(), dt.date())
        self.assertEqual(x.time(), dt.time())

        # Replacing with different tzinfo does adjust.
        got = dt.astimezone(fm5h)
        self.assertIs(got.tzinfo, fm5h)
        self.assertEqual(got.utcoffset(), timedelta(hours=-5))
        expected = dt - dt.utcoffset()  # in effect, convert to UTC
        expected += fm5h.utcoffset(dt)  # and from there to local time
        expected = expected.replace(tzinfo=fm5h) # and attach new tzinfo
        self.assertEqual(got.date(), expected.date())
        self.assertEqual(got.time(), expected.time())
        self.assertEqual(got.timetz(), expected.timetz())
        self.assertIs(got.tzinfo, expected.tzinfo)
        self.assertEqual(got, expected) 
Example 11
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_bogus_dst(self):
        class ok(tzinfo):
            def utcoffset(self, dt): return HOUR
            def dst(self, dt): return HOUR

        now = self.theclass.now().replace(tzinfo=utc_real)
        # Doesn't blow up.
        now.astimezone(ok())

        # Does blow up.
        class notok(ok):
            def dst(self, dt): return None
        self.assertRaises(ValueError, now.astimezone, notok()) 
Example 12
Project: Komok-protect   Author: Bajigur2   File: SKJEPANG01.py    GNU General Public License v3.0 5 votes vote down vote up
def a2():
    now2 = datetime.now()
    nowT = datetime.strftime(now2,"%M")
    if nowT[14:] in ["10","20","30","40","50","00"]:
        return False
    else:
        return True 
Example 13
Project: Komok-protect   Author: Bajigur2   File: SKJEPANG01.py    GNU General Public License v3.0 5 votes vote down vote up
def nameUpdate():
    while True:
        try:
        #while a2():
            #pass
            if wait["clock"] == True:
                now2 = datetime.now()
                nowT = datetime.strftime(now2,"༺%H:%M༻")
                profile = cl.getProfile()
                profile.displayName = wait["cName"] + nowT
                cl.updateProfile(profile)
            time.sleep(600)
        except:
            pass 
Example 14
Project: Komok-protect   Author: Bajigur2   File: SKJEPANG.py    GNU General Public License v3.0 5 votes vote down vote up
def a2():
    now2 = datetime.now()
    nowT = datetime.strftime(now2,"%M")
    if nowT[14:] in ["10","20","30","40","50","00"]:
        return False
    else:
        return True 
Example 15
Project: Komok-protect   Author: Bajigur2   File: SKJEPANG.py    GNU General Public License v3.0 5 votes vote down vote up
def nameUpdate():
    while True:
        try:
        #while a2():
            #pass
            if wait["clock"] == True:
                now2 = datetime.now()
                nowT = datetime.strftime(now2,"༺%H:%M༻")
                profile = cl.getProfile()
                profile.displayName = wait["cName"] + nowT
                cl.updateProfile(profile)
            time.sleep(600)
        except:
            pass 
Example 16
Project: Splunk_CBER_App   Author: MHaggis   File: client.py    MIT License 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, e:
                sleep(1) 
Example 17
Project: Splunk_CBER_App   Author: MHaggis   File: client.py    MIT License 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 18
Project: Splunk_CBER_App   Author: MHaggis   File: client.py    MIT License 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 19
Project: sound-of-sunshine   Author: waldoj   File: sunshine.py    MIT License 5 votes vote down vote up
def export_json():
    """Store the past 12 hours of power use and generation data in a file."""
    cursor.execute("SELECT datetime(time, 'unixepoch', 'localtime') AS time, \
                    used, generated, label, change, temp_int \
                    FROM energy \
                    WHERE time >= (strftime('%s','now') - (60 * 60 * 12)) \
                    ORDER BY time DESC")
    records = cursor.fetchmany(10000)

    # Drop 90% of data points -- we have too many to chart reasonably. We
    # iterate through in reverse because going in order while deleting records
    # makes a mess.
    num_records = len(records)
    i=0
    for j in range(num_records):
        reverse_i = num_records - 1 - j
        if records[reverse_i]['generated'] > 0:
            continue
        if i%9 != 0:
            records.pop(reverse_i)
        i+=1

    output = {}
    output['history'] = records
    
    output['today'] = daily_cumulative()
    try:
        solar_data['energy_today']
    except NameError:
        pass
    else:
        output['today']['generated'] = solar_data['energy_today']
    output['current'] = get_current_status()

    f = open(CONFIG['status_file'], 'w')
    f.write(json.dumps(output))
    f.close() 
Example 20
Project: sound-of-sunshine   Author: waldoj   File: sunshine.py    MIT License 5 votes vote down vote up
def is_daylight():
    """Report whether the sun is up."""

    # If we've cached daylight data, and it's less than 3 days old, use it.
    if os.path.exists('.daylight'):
        file_status = os.stat('.daylight')
        if (int(time.time()) - file_status.st_mtime) < (60 * 60 * 72):
            schedule = json.loads(open('.daylight').read(10000))

    # If we don't have cached data, retrieve it.
    try:
        schedule
    except NameError:
        api_url = 'http://api.sunrise-sunset.org/json?lat=' \
            + CONFIG['location']['lat'] + '&lng=' + CONFIG['location']['lon']
        response = urllib.urlopen(api_url)
        schedule = json.loads(response.read())
        if schedule['status'] is 'OK':
            print 'Fatal error: sunrise/sunset times could not be determined'
            sys.exit(1)
        else:
            f = open('.daylight', 'w')
            f.write(json.dumps(schedule))
            f.close()
    else:
        pass

    from datetime import datetime, time
    now = datetime.now()
    print now.time()
    if datetime.strptime(schedule['results']['sunrise'].time(), '%I:%M:%S %p').time < now.time() \
        <= datetime.strptime(schedule['results']['sunset'], '%I:%M:%S %p').time:
        print "yup"
        sys.exit()
        return True
    else:
        print "nope"
        sys.exit()
        return False 
Example 21
Project: sound-of-sunshine   Author: waldoj   File: sunshine.py    MIT License 5 votes vote down vote up
def label_use():
    """Label identifable draws on the power."""

    # Get power use over the past 120 minutes.
    cursor.execute("SELECT time, used, label \
                    FROM energy \
                    WHERE used IS NOT NULL \
                    AND time >= (strftime('%s','now') - (60 * 120) ) \
                    ORDER BY time ASC")
    records = cursor.fetchall()

    # If the difference between two points in time matches a device's draw,
    # record that fact in the database.
    prior = 0
    prior_2 = 0
    for record in records:
        if record['label'] is not None:
            prior_2 = prior
            prior = record['used']
            continue
        change = abs(record['used'] - prior)
        change_2 = abs(record['used'] - prior_2)
        for device in CONFIG['devices']:
            if (change >= device['watts']['low'] and change <= device['watts']['high']) or \
                (change_2 >= device['watts']['low'] and change_2 <= device['watts']['high']):
                if record['used'] > prior:
                   state = "on"
                else:
                   state = "off"
                cursor.execute("UPDATE energy \
                                SET label = ?, change = ? \
                                WHERE time = ?",
                                (device['name'], state, record['time']))
                db.commit()
                break
        prior_2 = prior
        prior = record['used']

    return True 
Example 22
Project: pytest-freezegun   Author: ktosiek   File: test_freezegun.py    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 23
Project: pytest-freezegun   Author: ktosiek   File: test_freezegun.py    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 24
Project: pytest-freezegun   Author: ktosiek   File: test_freezegun.py    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 25
Project: misp42splunk   Author: remg427   File: client.py    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, e:
                sleep(1) 
Example 26
Project: misp42splunk   Author: remg427   File: client.py    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 27
Project: misp42splunk   Author: remg427   File: client.py    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 28
Project: misp42splunk   Author: remg427   File: client.py    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 29
Project: misp42splunk   Author: remg427   File: client.py    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 30
Project: misp42splunk   Author: remg427   File: client.py    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 31
Project: misp42splunk   Author: remg427   File: client.py    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 32
Project: misp42splunk   Author: remg427   File: client.py    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 33
Project: misp42splunk   Author: remg427   File: client.py    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 34
Project: d6tpipe   Author: d6t   File: pipe.py    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 35
Project: beavy   Author: beavyHQ   File: social_connection.py    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 
Example 36
Project: SBpro   Author: PHIEZUKE   File: UP1.py    GNU General Public License v3.0 5 votes vote down vote up
def delete_log1():
    ndt = datetime.now()
    for data in msg_dict1:
        if (datetime.utcnow() - cTime_to_datetime(msg_dict1[data]["createdTime"])) > datetime.timedelta(1):
            del msg_dict1[msg_id] 
Example 37
Project: SBpro   Author: PHIEZUKE   File: UP1.py    GNU General Public License v3.0 5 votes vote down vote up
def delete_log():
    ndt = datetime.now()
    for data in msg_dict:
        if (datetime.utcnow() - cTime_to_datetime(msg_dict[data]["createdTime"])) > datetime.timedelta(1):
            del msg_dict[msg_id] 
Example 38
Project: SplunkVersionControl   Author: gjanders   File: client.py    Apache License 2.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 39
Project: SplunkVersionControl   Author: gjanders   File: client.py    Apache License 2.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 40
Project: SplunkVersionControl   Author: gjanders   File: client.py    Apache License 2.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 41
Project: plexivity   Author: mutschler   File: helper.py    GNU General Public License v3.0 5 votes vote down vote up
def generateSSLCert():
    if not os.path.exists(os.path.join(config.DATA_DIR, 'plexivity.key')) or not os.path.exists(os.path.join(config.DATA_DIR, 'plexivity.crt')):
        logger.warning("plexivity was started with ssl support but no cert was found, trying to generating cert and key now")
        try:
            from OpenSSL import crypto, SSL
            from socket import gethostname

            
            # create a key pair
            k = crypto.PKey()
            k.generate_key(crypto.TYPE_RSA, 1024)
    
            # create a self-signed cert
            cert = crypto.X509()
            cert.get_subject().C = "US"
            cert.get_subject().ST = "plex land"
            cert.get_subject().L = "plex land"
            cert.get_subject().O = "plexivity"
            cert.get_subject().OU = "plexivity"
            cert.get_subject().CN = gethostname()
            cert.set_serial_number(1000)
            cert.gmtime_adj_notBefore(0)
            cert.gmtime_adj_notAfter(10*365*24*60*60)
            cert.set_issuer(cert.get_subject())
            cert.set_pubkey(k)
            cert.sign(k, 'sha1')
    
            open(os.path.join(config.DATA_DIR, 'plexivity.crt'), "wt").write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
            open(os.path.join(config.DATA_DIR, 'plexivity.key'), "wt").write(crypto.dump_privatekey(crypto.FILETYPE_PEM, k))
            logger.info("ssl cert and key generated and saved to: %s" % config.DATA_DIR)
        except:
            logger.error("unable to generate ssl key and cert") 
Example 42
Project: plexivity   Author: mutschler   File: helper.py    GNU General Public License v3.0 5 votes vote down vote up
def startScheduler():
    db.create_all()
    #create default roles!
    if not db.session.query(models.Role).filter(models.Role.name == "admin").first():
        admin_role = models.Role(name='admin', description='Administrator Role')
        user_role = models.Role(name='user', description='User Role')
        db.session.add(admin_role)
        db.session.add(user_role)
        db.session.commit()
        
    try:
        import tzlocal

        tz = tzlocal.get_localzone()
        logger.info("local timezone: %s" % tz)
    except:
        tz = None

    if not tz or tz.zone == "local":
        logger.error('Local timezone name could not be determined. Scheduler will display times in UTC for any log'
                 'messages. To resolve this set up /etc/timezone with correct time zone name.')
        tz = pytz.utc
    #in debug mode this is executed twice :(
    #DONT run flask in auto reload mode when testing this!
    scheduler = BackgroundScheduler(logger=sched_logger, timezone=tz)
    scheduler.add_job(notify.task, 'interval', seconds=config.SCAN_INTERVAL, max_instances=1,
                      start_date=datetime.datetime.now(tz) + datetime.timedelta(seconds=2))
    scheduler.start()
    sched = scheduler
    #notify.task() 
Example 43
Project: wanggeService   Author: pchaos   File: test_quantaxis.py    MIT License 5 votes vote down vote up
def test_QA_fetch_indexlisting(self):
        # 从网上获取指数/基金日线
        qa.QA_util_log_info('从网上获取指数/基金日线')
        df = qa.QAFetch.QATdx.QA_fetch_get_stock_list('index')
        querysetlist = []
        for i in df.index[:10]:
            a = df.loc[i]
            # 本地获取指数日线数据
            data = qa.QA_fetch_index_day_adv(a.code, '1990-01-01', str(datetime.date.today()))
            """
            从本地数据库获取数据
            data = qa.QA_fetch_index_day_adv(a.code, '1990-01-01', datetime.now().strftime("%Y-%m-%d"))
            从网络获取数据
            data = qa.QAFetch.QATdx.QA_fetch_get_index_day(code, '2017-01-01', '2017-09-01')
            """
            d = data.data.date[0].strftime("%Y-%m-%d")
            if a.sse == 'sh':
                market = 1
            else:
                market = 0
            category = 11
            querysetlist.append(
                Listing(code=a.code, name=a['name'], timeToMarket=d, volunit=a.volunit, decimalpoint=a.decimal_point,
                        category=category, market=market))
        Listing.objects.bulk_create(querysetlist)
        self.assertTrue(Listing.getlist('index').count() > 0, '未插入成功:{}'.format(querysetlist)) 
Example 44
Project: bamboo-timeoffs   Author: canelmas   File: time_off_reminder.py    Apache License 2.0 5 votes vote down vote up
def __format_time_offs_in_html(members, team_name):

        content = TimeOffReminder.start_html(team_name)

        content_this_month = TimeOffReminder.start_a_month(datetime.now())
        content_next_month = TimeOffReminder.start_a_month(datetime.now() + relativedelta(months=1))

        for member in members:

            if member.time_offs:
                time_offs_this_month = member.get_time_offs_this_month()

                if time_offs_this_month:
                    for t in time_offs_this_month:
                        TimeOffReminder.add_time_off(content_this_month, t)
                else:
                    TimeOffReminder.no_time_off(content_this_month, member)

                time_offs_next_month = member.get_time_offs_next_month()

                if time_offs_next_month:
                    for t in time_offs_next_month:
                        TimeOffReminder.add_time_off(content_next_month, t)
                else:
                    TimeOffReminder.no_time_off(content_next_month, member)

            else:
                TimeOffReminder.no_time_off(content_this_month, member)
                TimeOffReminder.no_time_off(content_next_month, member)

        full_content = content + content_this_month + content_next_month
        TimeOffReminder.end_html(full_content)

        return ''.join(full_content) 
Example 45
Project: project-dev-kpis   Author: soundcloud   File: inventory.py    MIT License 5 votes vote down vote up
def monitor_inventory_metrics(synonym_mappings):
    global REPO_SCRAPE_TIMES

    minus_three_months = (datetime.now() - timedelta(3 * 365 / 12)).isoformat().split('.')[0]

    def git():
        return Github(get_access_token())

    for repo in git().search_repositories(
            ('org:%s archived:false pushed:>' % GITHUB_ORGANIZATION) + minus_three_months):
        owner = get_owner(synonym_mappings, repo)

        REPO_SCRAPE_TIMES[(owner, repo.name)] = time.time()

        pulls = list(repo.get_pulls())

        observe_inventory(owner, repo.name, pulls)

        manifests = [None]

        try:
            manifests = list(git().search_code(
                'repo:%s/%s language:json filename:*manifest*.json' % (GITHUB_ORGANIZATION, repo.name)))
        except GithubException:
            logger.error('Could not search repo %s!' % repo.name)

        observe_features(owner, repo.name, manifests)

    # zero-out deleted repos
    dead_repos = {tup: last_time for tup, last_time in REPO_SCRAPE_TIMES.iteritems() if
                  last_time < time.time() - 60 * 60}

    for owner, repo_name in dead_repos.keys():
        del REPO_SCRAPE_TIMES[(owner, repo_name)]
        observe_inventory(owner, repo_name, []) 
Example 46
Project: Deep_reinforcement_active_learning   Author: hoxmark   File: utils.py    MIT License 5 votes vote down vote up
def test_local_logger(inp):
    """function that return an logger-object to saving tensorboard logs locally"""
    logger_name = '{}'.format(datetime.now().strftime("%d-%m-%y_%H:%M"))
    basename = "./logs/test/"
    lg = LocalLogger('{}{}_{}'.format(
        basename,
        logger_name,
        inp
    ))

    return lg 
Example 47
Project: grand_central   Author: amiracle   File: client.py    MIT License 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, e:
                sleep(1) 
Example 48
Project: grand_central   Author: amiracle   File: client.py    MIT License 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 49
Project: grand_central   Author: amiracle   File: client.py    MIT License 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 50
Project: SplunkForPCAP   Author: DanielSchwartz1   File: client.py    MIT License 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, e:
                sleep(1)