當前位置: 首頁>>代碼示例>>Python>>正文


Python datetime.today方法代碼示例

本文整理匯總了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
# ------------------------------------------------------------------------------ 
開發者ID:ffplayout,項目名稱:ffplayout-engine,代碼行數:23,代碼來源:utils.py

示例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) 
開發者ID:wheever,項目名稱:ProxHTTPSProxyMII,代碼行數:22,代碼來源:ProxyTool.py

示例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'),
            }
        }) 
開發者ID:macarthur-lab,項目名稱:seqr,代碼行數:20,代碼來源:external_api_2_3_tests.py

示例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() 
開發者ID:openSUSE,項目名稱:openSUSE-release-tools,代碼行數:22,代碼來源:abichecker-dbcli.py

示例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)])) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:22,代碼來源:test_tools.py

示例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 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:18,代碼來源:test_date_range.py

示例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) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:23,代碼來源:test_strings.py

示例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) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:20,代碼來源:test_strings.py

示例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) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:26,代碼來源:test_strings.py

示例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) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:25,代碼來源:test_strings.py

示例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) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:24,代碼來源:test_strings.py

示例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) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:18,代碼來源:test_timestamp.py

示例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)) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:21,代碼來源:test_timestamp.py

示例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) 
開發者ID:monarch-initiative,項目名稱:dipper,代碼行數:27,代碼來源:Dataset.py

示例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') 
開發者ID:protream,項目名稱:iquery,代碼行數:20,代碼來源:trains.py


注:本文中的datetime.datetime.today方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。