本文整理匯總了Python中datetime.datetime.now方法的典型用法代碼示例。如果您正苦於以下問題:Python datetime.now方法的具體用法?Python datetime.now怎麽用?Python datetime.now使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類datetime.datetime
的用法示例。
在下文中一共展示了datetime.now方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: add_token
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import now [as 別名]
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
示例2: transfer_bankcard
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import now [as 別名]
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)
示例3: ip_whitelist_add
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import now [as 別名]
def ip_whitelist_add(ip_to_allow, info_record_dict=None):
"""添加ip到白名單, 並寫入文件"""
if ip_to_allow in single_ip_allowed_set:
return
dbgprint('ip white added', ip_to_allow, 'info:', info_record_dict)
single_ip_allowed_set.add(ip_to_allow)
is_ip_not_in_allow_range.cache_clear()
append_ip_whitelist_file(ip_to_allow)
# dbgprint(single_ip_allowed_set)
try:
with open(zmirror_root(human_ip_verification_whitelist_log), 'a', encoding='utf-8') as fp:
fp.write(datetime.now().strftime('%Y-%m-%d %H:%M:%S') + " " + ip_to_allow
+ " " + str(request.user_agent)
+ " " + repr(info_record_dict) + "\n")
except: # coverage: exclude
errprint('Unable to write log file', os.path.abspath(human_ip_verification_whitelist_log))
traceback.print_exc()
示例4: create_environment_task
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import now [as 別名]
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
示例5: create_file_logger
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import now [as 別名]
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
示例6: start
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import now [as 別名]
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
示例7: log_config
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import now [as 別名]
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)
示例8: test_current_mmyy_on_no_setdate
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import now [as 別名]
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'}
示例9: check
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import now [as 別名]
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
示例10: __init__
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import now [as 別名]
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
示例11: get
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import now [as 別名]
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}")
示例12: reap
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import now [as 別名]
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))
示例13: run
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import now [as 別名]
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)
示例14: test_json
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import now [as 別名]
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)
示例15: get_status_summary
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import now [as 別名]
def get_status_summary(trial_results: List[MutantTrialResult]) -> Dict[str, Union[str, int]]:
"""Create a status summary dictionary for later formatting.
Args:
trial_results: list of mutant trials
Returns:
Dictionary with keys for formatting in the report
"""
status: Dict[str, Union[str, int]] = dict(Counter([t.status for t in trial_results]))
status["TOTAL RUNS"] = len(trial_results)
status["RUN DATETIME"] = str(datetime.now())
return status