本文整理汇总了Python中datetime.datetime.today方法的典型用法代码示例。如果您正苦于以下问题:Python datetime.today方法的具体用法?Python datetime.today怎么用?Python datetime.today使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类datetime.datetime
的用法示例。
在下文中一共展示了datetime.today方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_time
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import today [as 别名]
def get_time(time_format):
"""
get different time formats:
- full_sec > current time in seconds
- stamp > current date time in seconds
- else > current time in HH:MM:SS
"""
t = datetime.today()
if time_format == 'full_sec':
return t.hour * 3600 + t.minute * 60 + t.second \
+ t.microsecond / 1000000
elif time_format == 'stamp':
return float(datetime.now().timestamp())
else:
return t.strftime('%H:%M:%S')
# ------------------------------------------------------------------------------
# default variables and values
# ------------------------------------------------------------------------------
示例2: sendout_error
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import today [as 别名]
def sendout_error(self, url, code, message=None, explain=None):
"Modified from http.server.send_error() for customized display"
try:
shortmsg, longmsg = self.responses[code]
except KeyError:
shortmsg, longmsg = '???', '???'
if message is None:
message = shortmsg
if explain is None:
explain = longmsg
content = (message_format %
{'code': code, 'message': message, 'explain': explain,
'url': url, 'now': datetime.today(), 'server': self.server_version})
body = content.encode('UTF-8', 'replace')
self.send_response_only(code, message)
self.send_header("Content-Type", self.error_content_type)
self.send_header('Content-Length', int(len(body)))
self.end_headers()
if self.command != 'HEAD' and code >= 200 and code not in (204, 304):
self.wfile.write(body)
示例3: test_mme_metrics_proxy
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import today [as 别名]
def test_mme_metrics_proxy(self):
url = '/api/matchmaker/v1/metrics'
self._check_mme_authenticated(url)
response = self._make_mme_request(url, 'get')
self.assertEqual(response.status_code, 200)
self.assertDictEqual(response.json(), {
'metrics': {
'numberOfCases': 3,
'numberOfSubmitters': 2,
'numberOfUniqueGenes': 4,
'numberOfUniqueFeatures': 4,
'numberOfRequestsReceived': 3,
'numberOfPotentialMatchesSent': 1,
'dateGenerated': datetime.today().strftime('%Y-%m-%d'),
}
})
示例4: do_prune
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import today [as 别名]
def do_prune(self, subcmd, opts, days):
"""${cmd_name}: prune old records
${cmd_usage}
${cmd_option_list}
"""
oldest = datetime.today() - timedelta(days = 365)
requests = self.session.query(DB.Request).filter(DB.Request.t_updated < oldest)
for req in requests:
for a in req.abichecks:
self.logger.info('prune %s %s %s', req.id, a.dst_project, a.dst_package)
for r in a.reports:
fn = os.path.join(CACHEDIR, r.htmlreport)
if os.path.exists(fn):
self.logger.info('removing %s', r.htmlreport)
os.unlink(fn)
self.session.delete(req)
self.session.commit()
示例5: test_datetime_bool
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import today [as 别名]
def test_datetime_bool(self, cache):
# GH13176
with pytest.raises(TypeError):
to_datetime(False)
assert to_datetime(False, errors="coerce", cache=cache) is NaT
assert to_datetime(False, errors="ignore", cache=cache) is False
with pytest.raises(TypeError):
to_datetime(True)
assert to_datetime(True, errors="coerce", cache=cache) is NaT
assert to_datetime(True, errors="ignore", cache=cache) is True
with pytest.raises(TypeError):
to_datetime([False, datetime.today()], cache=cache)
with pytest.raises(TypeError):
to_datetime(['20130101', True], cache=cache)
tm.assert_index_equal(to_datetime([0, False, NaT, 0.0],
errors="coerce", cache=cache),
DatetimeIndex([to_datetime(0, cache=cache),
NaT,
NaT,
to_datetime(0, cache=cache)]))
示例6: test_date_range_normalize
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import today [as 别名]
def test_date_range_normalize(self):
snap = datetime.today()
n = 50
rng = date_range(snap, periods=n, normalize=False, freq='2D')
offset = timedelta(2)
values = DatetimeIndex([snap + i * offset for i in range(n)])
tm.assert_index_equal(rng, values)
rng = date_range('1/1/2000 08:15', periods=n, normalize=False,
freq='B')
the_time = time(8, 15)
for val in rng:
assert val.time() == the_time
示例7: test_title
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import today [as 别名]
def test_title(self):
values = Series(["FOO", "BAR", NA, "Blah", "blurg"])
result = values.str.title()
exp = Series(["Foo", "Bar", NA, "Blah", "Blurg"])
tm.assert_series_equal(result, exp)
# mixed
mixed = Series(["FOO", NA, "bar", True, datetime.today(), "blah", None,
1, 2.])
mixed = mixed.str.title()
exp = Series(["Foo", NA, "Bar", NA, NA, "Blah", NA, NA, NA])
tm.assert_almost_equal(mixed, exp)
# unicode
values = Series([u("FOO"), NA, u("bar"), u("Blurg")])
results = values.str.title()
exp = Series([u("Foo"), NA, u("Bar"), u("Blurg")])
tm.assert_series_equal(results, exp)
示例8: test_capitalize
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import today [as 别名]
def test_capitalize(self):
values = Series(["FOO", "BAR", NA, "Blah", "blurg"])
result = values.str.capitalize()
exp = Series(["Foo", "Bar", NA, "Blah", "Blurg"])
tm.assert_series_equal(result, exp)
# mixed
mixed = Series(["FOO", NA, "bar", True, datetime.today(), "blah", None,
1, 2.])
mixed = mixed.str.capitalize()
exp = Series(["Foo", NA, "Bar", NA, NA, "Blah", NA, NA, NA])
tm.assert_almost_equal(mixed, exp)
# unicode
values = Series([u("FOO"), NA, u("bar"), u("Blurg")])
results = values.str.capitalize()
exp = Series([u("Foo"), NA, u("Bar"), u("Blurg")])
tm.assert_series_equal(results, exp)
示例9: test_len
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import today [as 别名]
def test_len(self):
values = Series(['foo', 'fooo', 'fooooo', np.nan, 'fooooooo'])
result = values.str.len()
exp = values.map(lambda x: len(x) if notna(x) else NA)
tm.assert_series_equal(result, exp)
# mixed
mixed = Series(['a_b', NA, 'asdf_cas_asdf', True, datetime.today(),
'foo', None, 1, 2.])
rs = Series(mixed).str.len()
xp = Series([3, NA, 13, NA, NA, 3, NA, NA, NA])
assert isinstance(rs, Series)
tm.assert_almost_equal(rs, xp)
# unicode
values = Series([u('foo'), u('fooo'), u('fooooo'), np.nan, u(
'fooooooo')])
result = values.str.len()
exp = values.map(lambda x: len(x) if notna(x) else NA)
tm.assert_series_equal(result, exp)
示例10: test_findall
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import today [as 别名]
def test_findall(self):
values = Series(['fooBAD__barBAD', NA, 'foo', 'BAD'])
result = values.str.findall('BAD[_]*')
exp = Series([['BAD__', 'BAD'], NA, [], ['BAD']])
tm.assert_almost_equal(result, exp)
# mixed
mixed = Series(['fooBAD__barBAD', NA, 'foo', True, datetime.today(),
'BAD', None, 1, 2.])
rs = Series(mixed).str.findall('BAD[_]*')
xp = Series([['BAD__', 'BAD'], NA, [], NA, NA, ['BAD'], NA, NA, NA])
assert isinstance(rs, Series)
tm.assert_almost_equal(rs, xp)
# unicode
values = Series([u('fooBAD__barBAD'), NA, u('foo'), u('BAD')])
result = values.str.findall('BAD[_]*')
exp = Series([[u('BAD__'), u('BAD')], NA, [], [u('BAD')]])
tm.assert_almost_equal(result, exp)
示例11: test_strip_lstrip_rstrip_mixed
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import today [as 别名]
def test_strip_lstrip_rstrip_mixed(self):
# mixed
mixed = Series([' aa ', NA, ' bb \t\n', True, datetime.today(), None,
1, 2.])
rs = Series(mixed).str.strip()
xp = Series(['aa', NA, 'bb', NA, NA, NA, NA, NA])
assert isinstance(rs, Series)
tm.assert_almost_equal(rs, xp)
rs = Series(mixed).str.lstrip()
xp = Series(['aa ', NA, 'bb \t\n', NA, NA, NA, NA, NA])
assert isinstance(rs, Series)
tm.assert_almost_equal(rs, xp)
rs = Series(mixed).str.rstrip()
xp = Series([' aa', NA, ' bb', NA, NA, NA, NA, NA])
assert isinstance(rs, Series)
tm.assert_almost_equal(rs, xp)
示例12: test_today
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import today [as 别名]
def test_today(self):
ts_from_string = Timestamp('today')
ts_from_method = Timestamp.today()
ts_datetime = datetime.today()
ts_from_string_tz = Timestamp('today', tz='US/Eastern')
ts_from_method_tz = Timestamp.today(tz='US/Eastern')
# Check that the delta between the times is less than 1s (arbitrarily
# small)
delta = Timedelta(seconds=1)
assert abs(ts_from_method - ts_from_string) < delta
assert abs(ts_datetime - ts_from_method) < delta
assert abs(ts_from_method_tz - ts_from_string_tz) < delta
assert (abs(ts_from_string_tz.tz_localize(None) -
ts_from_method_tz.tz_localize(None)) < delta)
示例13: test_class_ops_dateutil
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import today [as 别名]
def test_class_ops_dateutil(self):
def compare(x, y):
assert (int(np.round(Timestamp(x).value / 1e9)) ==
int(np.round(Timestamp(y).value / 1e9)))
compare(Timestamp.now(), datetime.now())
compare(Timestamp.now('UTC'), datetime.now(tzutc()))
compare(Timestamp.utcnow(), datetime.utcnow())
compare(Timestamp.today(), datetime.today())
current_time = calendar.timegm(datetime.now().utctimetuple())
compare(Timestamp.utcfromtimestamp(current_time),
datetime.utcfromtimestamp(current_time))
compare(Timestamp.fromtimestamp(current_time),
datetime.fromtimestamp(current_time))
date_component = datetime.utcnow()
time_component = (date_component + timedelta(minutes=10)).time()
compare(Timestamp.combine(date_component, time_component),
datetime.combine(date_component, time_component))
示例14: _set_version_level_triples
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import today [as 别名]
def _set_version_level_triples(self):
self.model.addType(self.version_level_curie, self.globaltt['Dataset'])
self.graph.addTriple(self.version_level_curie, self.globaltt['title'],
self.ingest_title +
" Monarch version " +
self.data_release_version,
True)
if self.ingest_description is not None:
self.model.addDescription(self.version_level_curie,
self.ingest_description)
self.graph.addTriple(self.version_level_curie, self.globaltt['Date Created'],
Literal(datetime.today().strftime("%Y%m%d"),
datatype=XSD.date))
self.graph.addTriple(self.version_level_curie, self.globaltt['version'],
Literal(self.data_release_version, datatype=XSD.date))
self.graph.addTriple(self.version_level_curie, self.globaltt['creator'],
self.curie_map.get("")) # eval's to MI.org
self.graph.addTriple(self.version_level_curie, self.globaltt['Publisher'],
self.curie_map.get("")) # eval's to MI.org
self.graph.addTriple(self.version_level_curie, self.globaltt['isVersionOf'],
self.summary_level_curie, object_is_literal=False)
self.graph.addTriple(self.version_level_curie,
self.globaltt['distribution'],
self.distribution_level_turtle_curie,
object_is_literal=False)
示例15: _valid_date
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import today [as 别名]
def _valid_date(self):
"""Check and return a valid query date."""
date = self._parse_date(self.date)
if not date:
exit_after_echo(INVALID_DATE)
try:
date = datetime.strptime(date, '%Y%m%d')
except ValueError:
exit_after_echo(INVALID_DATE)
# A valid query date should within 50 days.
offset = date - datetime.today()
if offset.days not in range(-1, 50):
exit_after_echo(INVALID_DATE)
return datetime.strftime(date, '%Y-%m-%d')