Python datetime.datetime.now() Examples

The following are 30 code examples of datetime.datetime.now(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module datetime.datetime , or try the search function .
Example #1
Source File: fabfile.py    From django-template with MIT License 8 votes vote down vote up
def create_environment_task(name, env_conf):
    """
    Create a task function from an environment name
    """

    @task(name=name)
    def load_environment(ctx):
        conf = env_conf.copy()
        conf["environment"] = name
        # So now conf is the ENVIRONMENTS[env] dict plus "environment" pointing to the name
        # Push them in the context config dict
        ctx.config.load_overrides(conf)
        # Add the common_settings in there
        ctx.conn = CustomConnection(host=conf["host"], inline_ssh_env=True)
        ctx.conn.config.load_overrides(conf)

    load_environment.__doc__ = (
        """Prepare connection and load config for %s environment""" % name
    )
    return load_environment 
Example #2
Source File: a3c.py    From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 8 votes vote down vote up
def log_config(log_dir=None, log_file=None, prefix=None, rank=0):
    reload(logging)
    head = '%(asctime)-15s Node[' + str(rank) + '] %(message)s'
    if log_dir:
        logging.basicConfig(level=logging.DEBUG, format=head)
        if not os.path.exists(log_dir):
            os.makedirs(log_dir)
        if not log_file:
            log_file = (prefix if prefix else '') + datetime.now().strftime('_%Y_%m_%d-%H_%M.log')
            log_file = log_file.replace('/', '-')
        else:
            log_file = log_file
        log_file_full_name = os.path.join(log_dir, log_file)
        handler = logging.FileHandler(log_file_full_name, mode='w')
        formatter = logging.Formatter(head)
        handler.setFormatter(formatter)
        logging.getLogger().addHandler(handler)
        logging.info('start with arguments %s', args)
    else:
        logging.basicConfig(level=logging.DEBUG, format=head)
        logging.info('start with arguments %s', args) 
Example #3
Source File: run.py    From mutatest with MIT License 7 votes vote down vote up
def clean_trial(src_loc: Path, test_cmds: List[str]) -> timedelta:
    """Remove all existing cache files and run the test suite.

    Args:
        src_loc: the directory of the package for cache removal, may be a file
        test_cmds: test running commands for subprocess.run()

    Returns:
        None

    Raises:
        BaselineTestException: if the clean trial does not pass from the test run.
    """
    cache.remove_existing_cache_files(src_loc)

    LOGGER.info("Running clean trial")

    # clean trial will show output all the time for diagnostic purposes
    start = datetime.now()
    clean_run = subprocess.run(test_cmds, capture_output=False)
    end = datetime.now()

    if clean_run.returncode != 0:
        raise BaselineTestException(
            f"Clean trial does not pass, mutant tests will be meaningless.\n"
            f"Output: {str(clean_run.stdout)}"
        )

    return end - start


####################################################################################################
# MUTATION SAMPLE GENERATION
#################################################################################################### 
Example #4
Source File: loop.py    From query-exporter with GNU General Public License v3.0 6 votes vote down vote up
def start(self):
        """Start timed queries execution."""
        for db in self._databases:
            try:
                await db.connect()
            except DataBaseError:
                self._increment_db_error_count(db)

        for query in self._timed_queries:
            if query.interval:
                call = PeriodicCall(self._run_query, query)
                call.start(query.interval)
            else:
                call = TimedCall(self._run_query, query)
                now = datetime.now().replace(tzinfo=gettz())
                cron_iter = croniter(query.schedule, now)

                def times_iter():
                    while True:
                        delta = next(cron_iter) - time.time()
                        yield self._loop.time() + delta

                call.start(times_iter())
            self._timed_calls[query.name] = call 
Example #5
Source File: user.py    From hydrus with MIT License 6 votes vote down vote up
def add_token(request: LocalProxy, session: Session) -> str:
    """
    Create a new token for the user or return a
    valid existing token to the user.
    """
    token = None
    id_ = int(request.authorization['username'])
    try:
        token = session.query(Token).filter(Token.user_id == id_).one()
        if not token.is_valid():
            update_token = '%030x' % randrange(16**30)
            token.id = update_token
            token.timestamp = datetime.now()
            session.commit()
    except NoResultFound:
        token = '%030x' % randrange(16**30)
        new_token = Token(user_id=id_, id=token)
        session.add(new_token)
        session.commit()
        return token
    return token.id 
Example #6
Source File: test_json.py    From wuy with GNU General Public License v2.0 6 votes vote down vote up
def test_json():
    def test(j, testType=None):
        def testSUS(obj, testType=None):
            s = wuy.jDumps(obj)
            nobj = wuy.jLoads(s)
            assert type(nobj) == testType

        testSUS(dict(v=j), dict)
        testSUS([j, dict(a=[j])], list)
        testSUS(j, testType)

    class Ob:
        def __init__(self):
            self.name = "koko"

    test(datetime.now(), datetime)
    test(date(1983, 5, 20), datetime)
    test(b"kkk", str)
    test("kkk", str)
    test(42, int)
    test(4.2, float)
    test(None, type(None))
    test(Ob(), dict)
    test(datetime.now() - datetime.now(), str) 
Example #7
Source File: transfer.py    From wechatpy with MIT License 6 votes vote down vote up
def transfer_bankcard(self, true_name, bank_card_no, bank_code, amount, desc=None, out_trade_no=None):
        """
        企业付款到银行卡接口

        :param true_name: 开户人名称
        :param bank_card_no: 银行卡号
        :param bank_code: 银行编号
        :param amount: 付款金额,单位分
        :param desc: 付款说明
        :param out_trade_no: 可选,商户订单号,需保持唯一性,默认自动生成
        :return: 返回的结果信息
        """
        if not out_trade_no:
            now = datetime.now()
            out_trade_no = f"{self.mch_id}{now.strftime('%Y%m%d%H%M%S')}{random.randint(1000, 10000)}"
        data = {
            "mch_id": self.mch_id,
            "partner_trade_no": out_trade_no,
            "amount": amount,
            "desc": desc,
            "enc_bank_no": self._rsa_encrypt(bank_card_no),
            "enc_true_name": self._rsa_encrypt(true_name),
            "bank_code": bank_code,
        }
        return self._post("mmpaysptrans/pay_bank", data=data) 
Example #8
Source File: log_api.py    From mlimages with MIT License 6 votes vote down vote up
def create_file_logger(root, name, file_name="log.txt", timestamp_format="", debug=False):
    file_api = FileAPI(root)
    timestamp = ""
    if timestamp_format:
        timestamp = datetime.now().strftime(timestamp_format)
    else:
        timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")

    folder = name + "_" + timestamp
    # prepare folder and file
    with file_api.open_with_mkdir(folder + "/" + file_name) as f:
        f.write("".encode("utf-8"))

    log_root = os.path.join(root, folder)
    logger = create_logger(name, debug)
    fh = FileHandler(os.path.join(log_root, file_name), encoding="utf-8")
    fh.setLevel(_bool_2_level(debug))
    logger.addHandler(fh)

    # add close method to release resource
    logger.close = types.MethodType(__close, logger)
    return logger, log_root 
Example #9
Source File: test_extractor_api.py    From comport with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_current_mmyy_on_no_setdate(self, testapp):
        ''' When there is no fixed date, it should send the current month and current year '''
        # set up the extractor
        department = Department.create(name="IM Police Department", short_name="IMPD", load_defaults=False)
        extractor, _ = Extractor.from_department_and_password(department=department, password="password")

        # set the correct authorization
        testapp.authorization = ('Basic', (extractor.username, 'password'))

        # post a sample json object to the heartbeat URL
        response = testapp.post_json("/data/heartbeat", params={"heartbeat": "heartbeat"})

        # current month and year
        now = datetime.now()

        # assert that we got the expected response
        assert response.status_code == 200
        assert response.json_body['nextMonth'] == now.month
        assert response.json_body['nextYear'] == now.year
        assert response.json_body['received'] == {'heartbeat': 'heartbeat'} 
Example #10
Source File: ratelimit.py    From fishroom with GNU General Public License v3.0 6 votes vote down vote up
def check(self, room, cmd, period=30, count=5):
        key = self.key.format(room=room, cmd=cmd)
        l = self.r.llen(key)
        if l < count:
            self.trigger(room, cmd)
            return True

        self.r.ltrim(key, -count, -1)
        first = int(self.r.lindex(key, 0))
        now_ts = int(datetime.now(tz=tz).strftime("%s"))
        if now_ts - first <= period:
            return False

        self.trigger(room, cmd)
        return True

# vim: ts=4 sw=4 sts=4 expandtab 
Example #11
Source File: device.py    From python-lifx-sdk with MIT License 6 votes vote down vote up
def __init__(self, device_id, host, client):
        # Our Device
        self._device_id = device_id
        self._host = host

        # Services
        self._services = {}

        # Last seen time
        self._lastseen = datetime.now()

        # For sending packets
        self._client = client

        # Tools for tracking responses
        self._tracked = {}
        self._responses = {}

        # Stats tracking
        self._dropped_packets = 0
        self._sent_packets = 0 
Example #12
Source File: website.py    From pinnwand with MIT License 6 votes vote down vote up
def get(self, slug: str) -> None:  # type: ignore
        """Fetch paste from database and redirect to /slug if the paste
           exists."""
        with database.session() as session:
            paste = (
                session.query(database.Paste)
                .filter(database.Paste.slug == slug)
                .first()
            )

            if not paste:
                raise tornado.web.HTTPError(404)

            if paste.exp_date < datetime.now():
                session.delete(paste)
                session.commit()

                log.warn(
                    "RedirectShow.get: paste was expired, is your cronjob running?"
                )

                raise tornado.web.HTTPError(404)

            self.redirect(f"/{paste.slug}") 
Example #13
Source File: website.py    From pinnwand with MIT License 6 votes vote down vote up
def get(self, file_id: str) -> None:  # type: ignore
        """Get a file from the database and show it in the plain."""

        with database.session() as session:
            file = (
                session.query(database.File)
                .filter(database.File.slug == file_id)
                .first()
            )

            if not file:
                raise tornado.web.HTTPError(404)

            if file.paste.exp_date < datetime.now():
                session.delete(file.paste)
                session.commit()

                log.warn(
                    "FileRaw.get: paste was expired, is your cronjob running?"
                )

                raise tornado.web.HTTPError(404)

            self.set_header("Content-Type", "text/plain; charset=utf-8")
            self.write(file.raw) 
Example #14
Source File: website.py    From pinnwand with MIT License 6 votes vote down vote up
def get(self, file_id: str) -> None:  # type: ignore
        """Get a file from the database and show it in hex."""

        with database.session() as session:
            file = (
                session.query(database.File)
                .filter(database.File.slug == file_id)
                .first()
            )

            if not file:
                raise tornado.web.HTTPError(404)

            if file.paste.exp_date < datetime.now():
                session.delete(file.paste)
                session.commit()

                log.warn(
                    "FileRaw.get: paste was expired, is your cronjob running?"
                )

                raise tornado.web.HTTPError(404)

            self.set_header("Content-Type", "text/plain; charset=utf-8")
            self.write(binascii.hexlify(file.raw.encode("latin1"))) 
Example #15
Source File: command.py    From pinnwand with MIT License 6 votes vote down vote up
def reap() -> None:
    """Delete all pastes that are past their expiry date in pinnwand's
       database."""
    from pinnwand import database

    with database.session() as session:
        pastes = (
            session.query(database.Paste)
            .filter(database.Paste.exp_date < datetime.now())
            .all()
        )

        for paste in pastes:
            session.delete(paste)

        session.commit()

        log.info("reap: removed %d pastes", len(pastes)) 
Example #16
Source File: live_worker.py    From TradzQAI with Apache License 2.0 6 votes vote down vote up
def run(self):
        self.agent.reset()
        state = self.env.reset()
        self.is_working = True
        while self.is_working:
            if datetime.now().minute % 15 != 0:
                self.changed = False
            if datetime.now().minute % 15 == 0 and not self.changed:
                self.changed = True
                action = self.agent.act(state, deterministic=self.deterministic)
                state, terminal, reward = self.env.execute(action)
                #print (state)
                if "train" == self.env.mode:
                    self.agent.observe(reward=reward, terminal=terminal)
                if terminal and self.env.mode == "train":
                    self.agent.save_model(directory=self.env.saver.model_file_path,
                        append_timestep=True)
                if self.agent.should_stop() or self.env.stop:
                    break
            time.sleep(1) 
Example #17
Source File: dumpdb.py    From Servo with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def handle(self, *args, **options):
        s = settings.DATABASES['default']
        db, user, pw = s['NAME'], s['USER'], s['PASSWORD']
        fname  = datetime.now().strftime('%Y%m%d_%H%M') + '.pgdump'
        
        if not os.path.exists(settings.BACKUP_DIR):
            os.mkdir(settings.BACKUP_DIR)

        path = os.path.join(settings.BACKUP_DIR, fname)
        os.putenv('PGPASSWORD', pw)
        subprocess.call(['pg_dump', '-Fc',  db, '-U', user, '-f', path]) 
Example #18
Source File: layer.py    From tfont with Apache License 2.0 5 votes vote down vote up
def copy(self):
        global TFontConverter
        try:
            TFontConverter
        except NameError:
            from tfont.converters.tfontConverter import TFontConverter
        conv = TFontConverter(indent=None)
        l = conv.structure(conv.unstructure(self), self.__class__)
        l._name = datetime.now().strftime("%b %d %y {} %H:%M").format("–")
        l.visible = False
        return l 
Example #19
Source File: ratelimit.py    From fishroom with GNU General Public License v3.0 5 votes vote down vote up
def trigger(self, room, cmd):
        key = self.key.format(room=room, cmd=cmd)
        now_ts = datetime.now(tz=tz).strftime("%s")
        self.r.rpush(key, now_ts) 
Example #20
Source File: helpers.py    From fishroom with GNU General Public License v3.0 5 votes vote down vote up
def get_now_date_time():
    now = get_now()
    return now.strftime("%Y-%m-%d"), now.strftime("%H:%M:%S") 
Example #21
Source File: helpers.py    From fishroom with GNU General Public License v3.0 5 votes vote down vote up
def get_now():
    return datetime.now(tz=tz) 
Example #22
Source File: alexnet_benchmark.py    From DOTA_models with Apache License 2.0 5 votes vote down vote up
def time_tensorflow_run(session, target, info_string):
  """Run the computation to obtain the target tensor and print timing stats.

  Args:
    session: the TensorFlow session to run the computation under.
    target: the target Tensor that is passed to the session's run() function.
    info_string: a string summarizing this run, to be printed with the stats.

  Returns:
    None
  """
  num_steps_burn_in = 10
  total_duration = 0.0
  total_duration_squared = 0.0
  for i in xrange(FLAGS.num_batches + num_steps_burn_in):
    start_time = time.time()
    _ = session.run(target)
    duration = time.time() - start_time
    if i >= num_steps_burn_in:
      if not i % 10:
        print ('%s: step %d, duration = %.3f' %
               (datetime.now(), i - num_steps_burn_in, duration))
      total_duration += duration
      total_duration_squared += duration * duration
  mn = total_duration / FLAGS.num_batches
  vr = total_duration_squared / FLAGS.num_batches - mn * mn
  sd = math.sqrt(vr)
  print ('%s: %s across %d steps, %.3f +/- %.3f sec / batch' %
         (datetime.now(), info_string, FLAGS.num_batches, mn, sd)) 
Example #23
Source File: Self.py    From CyberTK-Self with GNU General Public License v2.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 #24
Source File: Self.py    From CyberTK-Self with GNU General Public License v2.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 #25
Source File: stock_match.py    From backtrader-cn with GNU General Public License v3.0 5 votes vote down vote up
def update_sina_stock_match():
    date = (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d')
    msg = get_market_signal_by_date(date)
    user = StockMatch(
        username=conf.SINA_CONFIG['username'],
        password=conf.SINA_CONFIG['password'],
    )
    for stock_code in msg['buy']:
        user.buy(stock_code)
        # 经过测试,每隔3S进行一次买入操作的频率最合适
        time.sleep(3)
    else:
        logger.info("没有股票需要买入") 
Example #26
Source File: mutators.py    From comport with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def alter_data(self, incident):
        if (random.random() > 1 / 12):
            incident["occuredDate"] = random_date(datetime.now() - timedelta(weeks=52), datetime.now() - timedelta(weeks=26)).strftime("%Y-%m-%d 0:0:00")
        else:
            incident["occuredDate"] = random_date(datetime.now() - timedelta(weeks=1), datetime.now()).strftime("%Y-%m-%d 0:0:00")
        return incident 
Example #27
Source File: mutators.py    From comport with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def alter_data(self, incident):
        incident["occuredDate"] = random_date(datetime.now() - timedelta(weeks=52), datetime.now() - timedelta(weeks=26)).strftime("%Y-%m-%d 0:0:00")

        return incident 
Example #28
Source File: views.py    From comport with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def heartbeat():
    username = request.authorization.username
    extractor = Extractor.query.filter_by(username=username).first()

    # set the extractor last contact datetime to now
    now = datetime.now()
    extractor.last_contact = now
    extractor.save()

    # get the month and year to tell the extractor to start from
    next_month = extractor.next_month if extractor.next_month else now.month
    next_year = extractor.next_year if extractor.next_year else now.year

    #
    # build and send a Slack notification about this ping
    slack_body_lines = []
    extractor_department = extractor.first_department()
    if extractor_department:
        slack_body_lines.append('For: {}'.format(extractor_department.name))
    else:
        slack_body_lines.append('Username: {}'.format(username))

    slack_date_line = 'Replied with extraction start date: {}/{}'.format(next_month, next_year)

    slack_body_lines.append(slack_date_line)
    send_slack_message('Comport Pinged by Extractor!', slack_body_lines)

    #
    # remove records for this department from the incidents_updated table
    IncidentsUpdated.delete_records(department_id=extractor_department.id)

    # respond to the extractor
    heartbeat_response = json.dumps({"received": request.json, "nextMonth": next_month, "nextYear": next_year})
    return heartbeat_response 
Example #29
Source File: deploy.py    From aegea with Apache License 2.0 5 votes vote down vote up
def ls(args):
    """
    List status of all configured SNS-SQS message buses and instances subscribed to them.
    """
    table = []
    queues = list(resources.sqs.queues.filter(QueueNamePrefix="github"))
    max_age = datetime.now(tzutc()) - timedelta(days=15)
    for topic in resources.sns.topics.all():
        account_id = ARN(topic.arn).account_id
        try:
            bucket = resources.s3.Bucket("deploy-status-{}".format(account_id))
            status_objects = bucket.objects.filter(Prefix=ARN(topic.arn).resource)
            recent_status_objects = {o.key: o for o in status_objects if o.last_modified > max_age}
        except ClientError:
            continue
        if ARN(topic.arn).resource.startswith("github"):
            for queue in queues:
                queue_name = os.path.basename(queue.url)
                if queue_name.startswith(ARN(topic.arn).resource):
                    row = dict(Topic=topic, Queue=queue)
                    status_object = bucket.Object(os.path.join(queue_name, "status"))
                    if status_object.key not in recent_status_objects:
                        continue
                    try:
                        github, owner, repo, events, instance = os.path.dirname(status_object.key).split("-", 4)
                        status = json.loads(status_object.get()["Body"].read().decode("utf-8"))
                        row.update(status, Owner=owner, Repo=repo, Instance=instance,
                                   Updated=status_object.last_modified)
                    except Exception:
                        pass
                    table.append(row)
    args.columns = ["Owner", "Repo", "Instance", "Status", "Ref", "Commit", "Updated", "Topic", "Queue"]
    page_output(tabulate(table, args)) 
Example #30
Source File: user.py    From hydrus with MIT License 5 votes vote down vote up
def create_nonce(session: Session) -> str:
    """
    Create a one time use nonce valid for a short time
    for user authentication.
    """
    nonce = str(uuid4())
    time = datetime.now()
    new_nonce = Nonce(id=nonce, timestamp=time)
    session.add(new_nonce)
    session.commit()
    return nonce