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 |
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 |
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 |
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: user.py From hydrus with MIT License | 6 votes |
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 #5
Source File: transfer.py From wechatpy with MIT License | 6 votes |
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 #6
Source File: log_api.py From mlimages with MIT License | 6 votes |
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 #7
Source File: loop.py From query-exporter with GNU General Public License v3.0 | 6 votes |
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 #8
Source File: test_extractor_api.py From comport with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #9
Source File: ratelimit.py From fishroom with GNU General Public License v3.0 | 6 votes |
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 #10
Source File: device.py From python-lifx-sdk with MIT License | 6 votes |
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 #11
Source File: website.py From pinnwand with MIT License | 6 votes |
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 #12
Source File: website.py From pinnwand with MIT License | 6 votes |
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 #13
Source File: website.py From pinnwand with MIT License | 6 votes |
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 #14
Source File: command.py From pinnwand with MIT License | 6 votes |
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 #15
Source File: live_worker.py From TradzQAI with Apache License 2.0 | 6 votes |
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 #16
Source File: test_json.py From wuy with GNU General Public License v2.0 | 6 votes |
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 #17
Source File: random_robot.py From vergeml with MIT License | 5 votes |
def random_robot_name(moment_of_birth, dest=None): """Construct a random robot name. """ random.seed(moment_of_birth) adj = random.choice(_ADJ) noun = random.choice(_NOUN) name = "{}-{}".format(adj, noun).lower() if dest and os.path.exists(os.path.join(dest, name)): return random_robot_name(datetime.now(), dest) return name
Example #18
Source File: util.py From mlbv with GNU General Public License v3.0 | 5 votes |
def has_reached_time(datetime_val_utc): # return datetime_val_utc.replace(timezone.utc) < datetime.now(timezone.utc) return datetime_val_utc < datetime.now(timezone.utc)
Example #19
Source File: stream.py From mlbv with GNU General Public License v3.0 | 5 votes |
def _has_game_started(start_time_utc): return start_time_utc.replace(timezone.utc) < datetime.now(timezone.utc)
Example #20
Source File: user.py From hydrus with MIT License | 5 votes |
def check_nonce(request: LocalProxy, session: Session) -> bool: """check validity of nonce passed by the user.""" try: id_ = request.headers['X-Authentication'] nonce = session.query(Nonce).filter(Nonce.id == id_).one() present = datetime.now() present = present - nonce.timestamp session.delete(nonce) session.commit() if present > timedelta(0, 0, 0, 0, 1, 0, 0): return False except BaseException: return False return True
Example #21
Source File: user.py From hydrus with MIT License | 5 votes |
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
Example #22
Source File: stock_match.py From backtrader-cn with GNU General Public License v3.0 | 5 votes |
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 #23
Source File: deploy.py From aegea with Apache License 2.0 | 5 votes |
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 #24
Source File: audit.py From aegea with Apache License 2.0 | 5 votes |
def audit_1_1(self): """1.1 Avoid the use of the "root" account (Scored)""" for row in self.credential_report: if row["user"] == "<root_account>": for field in "password_last_used", "access_key_1_last_used_date", "access_key_2_last_used_date": if row[field] != "N/A" and self.parse_date(row[field]) > datetime.now(tzutc()) - timedelta(days=1): raise Exception("Root account last used less than a day ago ({})".format(field))
Example #25
Source File: audit.py From aegea with Apache License 2.0 | 5 votes |
def audit_1_3(self): """1.3 Ensure credentials unused for 90 days or greater are disabled (Scored)""" for row in self.credential_report: for access_key in "1", "2": if json.loads(row["access_key_{}_active".format(access_key)]): last_used = row["access_key_{}_last_used_date".format(access_key)] if last_used != "N/A" and self.parse_date(last_used) < datetime.now(tzutc()) - timedelta(days=90): msg = "Active access key {} in account {} last used over 90 days ago" raise Exception(msg.format(access_key, row["user"]))
Example #26
Source File: audit.py From aegea with Apache License 2.0 | 5 votes |
def audit_1_4(self): """1.4 Ensure access keys are rotated every 90 days or less (Scored)""" for row in self.credential_report: for access_key in "1", "2": if json.loads(row["access_key_{}_active".format(access_key)]): last_rotated = row["access_key_{}_last_rotated".format(access_key)] if self.parse_date(last_rotated) < datetime.now(tzutc()) - timedelta(days=90): msg = "Active access key {} in account {} last rotated over 90 days ago" raise Exception(msg.format(access_key, row["user"]))
Example #27
Source File: audit.py From aegea with Apache License 2.0 | 5 votes |
def audit_2_4(self): """2.4 Ensure CloudTrail trails are integrated with CloudWatch Logs (Scored)""" for trail in self.trails: self.assertIn("CloudWatchLogsLogGroupArn", trail) trail_status = clients.cloudtrail.get_trail_status(Name=trail["TrailARN"]) self.assertGreater(trail_status["LatestCloudWatchLogsDeliveryTime"], datetime.now(tzutc()) - timedelta(days=1))
Example #28
Source File: __init__.py From aegea with Apache License 2.0 | 5 votes |
def get_pricing_data(service_code, filters=None, max_cache_age_days=30): from ... import config if filters is None: filters = [("location", region_name(clients.ec2.meta.region_name))] get_products_args = dict(ServiceCode=service_code, Filters=[dict(Type="TERM_MATCH", Field=k, Value=v) for k, v in filters]) cache_key = hashlib.sha256(json.dumps(get_products_args, sort_keys=True).encode()).hexdigest()[:32] service_code_filename = os.path.join(config.user_config_dir, "pricing_cache_{}.json.gz".format(cache_key)) try: cache_date = datetime.fromtimestamp(os.path.getmtime(service_code_filename)) if cache_date < datetime.now() - timedelta(days=max_cache_age_days): raise Exception("Cache is too old, discard") with gzip.open(service_code_filename) as gz_fh: with io.BufferedReader(gz_fh) as buf_fh: pricing_data = json.loads(buf_fh.read().decode()) except Exception: logger.info("Fetching pricing data for %s", service_code) client = boto3.client("pricing", region_name="us-east-1") pricing_data = [json.loads(p) for p in paginate(client.get_paginator("get_products"), **get_products_args)] try: with gzip.open(service_code_filename, "w") as fh: fh.write(json.dumps(pricing_data).encode()) except Exception as e: print(e, file=sys.stderr) return pricing_data
Example #29
Source File: printing.py From aegea with Apache License 2.0 | 5 votes |
def format_datetime(d): from dateutil.tz import tzutc from babel import dates d = d.replace(microsecond=0) if not USING_PYTHON2: # Switch from UTC to local TZ d = d.astimezone(tz=None) return dates.format_timedelta(d - datetime.now(tzutc()), add_direction=True)
Example #30
Source File: sonarr.py From pkmeter with BSD 3-Clause "New" or "Revised" License | 5 votes |
def update(self): endstr = (datetime.now() + timedelta(days=14)).strftime(DATE_FORMAT) update_url = UPDATE_URL % {'host':self.host, 'apikey':self.apikey, 'end':endstr} response = utils.http_request(update_url).get('response') if response: content = json.loads(response.read().decode('utf-8')) self.data['shows'] = [e for e in content if not self._is_ignored(utils.rget(e, 'series.title'))] super(Plugin, self).update()