本文整理汇总了Python中datetime.now方法的典型用法代码示例。如果您正苦于以下问题:Python datetime.now方法的具体用法?Python datetime.now怎么用?Python datetime.now使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类datetime
的用法示例。
在下文中一共展示了datetime.now方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_freezing_time_in_fixture
# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import now [as 别名]
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
示例2: test_class_just_fixture
# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import now [as 别名]
def test_class_just_fixture(testdir):
testdir.makepyfile("""
from datetime import datetime
import time
class TestAsClass(object):
def test_just_fixture(self, freezer):
now = datetime.now()
time.sleep(0.1)
later = datetime.now()
assert now == later
""")
result = testdir.runpytest('-v', '-s')
assert result.ret == 0
示例3: observe_inventory
# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import now [as 别名]
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)
示例4: test_load_dates_timezones
# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import now [as 别名]
def test_load_dates_timezones():
from dataflows import Flow, checkpoint
from datetime import datetime, timezone
import shutil
dates = [
datetime.now(),
datetime.now(timezone.utc).astimezone()
]
shutil.rmtree('.checkpoints/test_load_dates_timezones', ignore_errors=True)
Flow(
[{'date': d.date(), 'datetime': d} for d in dates],
checkpoint('test_load_dates_timezones')
).process()
results = Flow(
checkpoint('test_load_dates_timezones')
).results()
assert list(map(lambda x: x['date'], results[0][0])) == \
list(map(lambda x: x.date(), dates))
assert list(map(lambda x: x['datetime'], results[0][0])) == \
list(map(lambda x: x, dates))
示例5: test_astimezone
# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import now [as 别名]
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
示例6: latest_post_date
# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import now [as 别名]
def latest_post_date(self):
"""
Return the latest item's pubdate or updateddate. If no items
have either of these attributes this return the current UTC date/time.
"""
latest_date = None
date_keys = ('updateddate', 'pubdate')
for item in self.items:
for date_key in date_keys:
item_date = item.get(date_key)
if item_date:
if latest_date is None or item_date > latest_date:
latest_date = item_date
# datetime.now(tz=utc) is slower, as documented in django.utils.timezone.now
return latest_date or datetime.datetime.utcnow().replace(tzinfo=utc)
示例7: describe
# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import now [as 别名]
def describe(self, as_tuple=None, **kwargs):
"""
This method is to retrieve test resources, method parameters are only used signature compatibility
:param as_tuple: Set to true to return results as immutable named dictionaries instead of dictionaries
:return: Test resource
"""
def create_resource(r):
return {
actions.ops_automator_test_action.TEST_RESOURCE_ID: OpsautomatortestService.resource_id(r),
"AwsAccount": self.aws_account,
"Region": kwargs["region"] if "region" in kwargs else self.region,
"Service": self.service_name,
"ResourceTypeName": actions.ops_automator_test_action.TEST_RESOURCE_NAMES[0],
"Tags": self.tags
}
start = datetime.now()
self._args = kwargs
result = [create_resource(i) for i in sorted(self._number_of_resources)]
if self._args.get(actions.ops_automator_test_action.PARAM_TEST_SELECT_FAILING, False) in ["True", True]:
raise Exception("Selection of resources fails")
select_time = int(self._args.get(actions.ops_automator_test_action.PARAM_TEST_SELECT_DURATION, 0))
if select_time != 0:
variance = float(self._args.get(actions.ops_automator_test_action.PARAM_TEST_SELECT_DURATION_VARIANCE, 0))
if variance != 0:
select_time += (random.uniform(variance * -1, variance) * select_time)
time_spend = (datetime.now() - start).total_seconds()
if time_spend < select_time:
time.sleep(select_time - time_spend)
return result
示例8: test_freezing_time
# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import now [as 别名]
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
示例9: test_no_mark
# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import now [as 别名]
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
示例10: test_fixture_no_mark
# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import now [as 别名]
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
示例11: test_fixture_freezes_time
# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import now [as 别名]
def test_fixture_freezes_time(testdir):
testdir.makepyfile("""
import time
def test_fixture_freezes_time(freezer):
now = time.time()
time.sleep(0.1)
later = time.time()
assert now == later
""")
result = testdir.runpytest('-v', '-s')
assert result.ret == 0
示例12: test_class_freezing_time
# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import now [as 别名]
def test_class_freezing_time(testdir):
testdir.makepyfile("""
import pytest
from datetime import date, datetime
class TestAsClass(object):
@pytest.mark.freeze_time('2017-05-20 15:42')
def test_sth(self):
assert datetime.now().date() == date(2017, 5, 20)
""")
result = testdir.runpytest('-v', '-s')
assert result.ret == 0
示例13: restart
# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import now [as 别名]
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.")
示例14: search
# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import now [as 别名]
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)
示例15: touch
# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import now [as 别名]
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