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


Python datetime.timedelta方法代碼示例

本文整理匯總了Python中datetime.datetime.timedelta方法的典型用法代碼示例。如果您正苦於以下問題:Python datetime.timedelta方法的具體用法?Python datetime.timedelta怎麽用?Python datetime.timedelta使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在datetime.datetime的用法示例。


在下文中一共展示了datetime.timedelta方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: test_simple_model_with_annual_licence_multi_year

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import timedelta [as 別名]
def test_simple_model_with_annual_licence_multi_year(simple_linear_model):
    """ Test the AnnualLicense over multiple years
    """
    import pandas as pd
    import datetime, calendar
    m = simple_linear_model
    # Modify model to run for 3 years of non-leap years at 30 day time-step.
    m.timestepper.start = pd.to_datetime('2017-1-1')
    m.timestepper.end = pd.to_datetime('2020-1-1')
    m.timestepper.delta = datetime.timedelta(30)

    annual_total = 365.0
    lic = AnnualLicense(m, m.nodes["Input"], annual_total)
    # Apply licence to the model
    m.nodes["Input"].max_flow = lic
    m.nodes["Output"].max_flow = 10.0
    m.nodes["Output"].cost = -10.0
    m.setup()

    for i in range(len(m.timestepper)):
        m.step()
        days_in_year = 365 + int(calendar.isleap(m.timestepper.current.datetime.year))
        assert_allclose(m.nodes["Output"].flow, annual_total/days_in_year) 
開發者ID:pywr,項目名稱:pywr,代碼行數:25,代碼來源:test_license.py

示例2: parse_age

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import timedelta [as 別名]
def parse_age(value=None):
    """Parses a base-10 integer count of seconds into a timedelta.

    If parsing fails, the return value is `None`.

    :param value: a string consisting of an integer represented in base-10
    :return: a :class:`datetime.timedelta` object or `None`.
    """
    if not value:
        return None
    try:
        seconds = int(value)
    except ValueError:
        return None
    if seconds < 0:
        return None
    try:
        return timedelta(seconds=seconds)
    except OverflowError:
        return None 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:22,代碼來源:http.py

示例3: dump_age

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import timedelta [as 別名]
def dump_age(age=None):
    """Formats the duration as a base-10 integer.

    :param age: should be an integer number of seconds,
                a :class:`datetime.timedelta` object, or,
                if the age is unknown, `None` (default).
    """
    if age is None:
        return
    if isinstance(age, timedelta):
        # do the equivalent of Python 2.7's timedelta.total_seconds(),
        # but disregarding fractional seconds
        age = age.seconds + (age.days * 24 * 3600)

    age = int(age)
    if age < 0:
        raise ValueError("age cannot be negative")

    return str(age) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:21,代碼來源:http.py

示例4: stop

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import timedelta [as 別名]
def stop(self):
        """Stop timer and print info message

        The info message will be only printed if `Timer.verbose` is *true*.

        Returns:
            A timedelta object.
        """
        if self.starttime is None:
            raise ValueError("Timer has not been started yet!")

        self.endtime = time.time()

        dt = timedelta(seconds=self.endtime - self.starttime)

        # If no additional information is specified add default information
        # to make the output more readable.
        if self.info is None:
            self.info = 'elapsed time'

        if self.verbose:
            # Connect additional information and measured time for output.
            print('{info}: {time}'.format(info=self.info, time=dt))

        return dt 
開發者ID:atmtools,項目名稱:typhon,代碼行數:27,代碼來源:timeutils.py

示例5: create_sas_token

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import timedelta [as 別名]
def create_sas_token(key_name, shared_access_key, scope, expiry=timedelta(hours=1)):
    """Create a SAS token.

    :param key_name: The username/key name/policy name for the token.
    :type key_name: bytes
    :param shared_access_key: The shared access key to generate the token from.
    :type shared_access_key: bytes
    :param scope: The token permissions scope.
    :type scope: bytes
    :param expiry: The lifetime of the generated token. Default is 1 hour.
    :type expiry: ~datetime.timedelta
    :rtype: bytes
    """
    shared_access_key = base64.b64encode(shared_access_key)
    abs_expiry = int(time.time()) + expiry.seconds
    return c_uamqp.create_sas_token(shared_access_key, scope, key_name, abs_expiry) 
開發者ID:Azure,項目名稱:azure-uamqp-python,代碼行數:18,代碼來源:utils.py

示例6: dump_age

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import timedelta [as 別名]
def dump_age(age=None):
    """Formats the duration as a base-10 integer.

    :param age: should be an integer number of seconds,
                a :class:`datetime.timedelta` object, or,
                if the age is unknown, `None` (default).
    """
    if age is None:
        return
    if isinstance(age, timedelta):
        # do the equivalent of Python 2.7's timedelta.total_seconds(),
        # but disregarding fractional seconds
        age = age.seconds + (age.days * 24 * 3600)

    age = int(age)
    if age < 0:
        raise ValueError('age cannot be negative')

    return str(age) 
開發者ID:ryfeus,項目名稱:lambda-packs,代碼行數:21,代碼來源:http.py

示例7: total_seconds

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import timedelta [as 別名]
def total_seconds(td):
    """
    Given a timedelta (*td*) return an integer representing the equivalent of
    Python 2.7's :meth:`datetime.timdelta.total_seconds`.
    """
    return (((
        td.microseconds +
        (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6))

# NOTE:  This is something I'm investigating as a way to use the new go_async
# module.  A work-in-progress.  Ignore for now... 
開發者ID:Wramberg,項目名稱:TerminalView,代碼行數:13,代碼來源:terminal.py

示例8: timeout

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import timedelta [as 別名]
def timeout(self):
        """
        A `property` that controls how long a key will last before being
        automatically removed.  May be be given as a `datetime.timedelta`
        object or a string like, "1d", "30s" (will be passed through the
        `convert_to_timedelta` function).
        """
        if not hasattr(self, "_timeout"):
            self._timeout = timedelta(hours=1) # Default is 1-hour timeout
        return self._timeout 
開發者ID:Wramberg,項目名稱:TerminalView,代碼行數:12,代碼來源:terminal.py

示例9: interval

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import timedelta [as 別名]
def interval(self):
        """
        A `property` that controls how often we check for expired keys.  May be
        given as milliseconds (integer), a `datetime.timedelta` object, or a
        string like, "1d", "30s" (will be passed through the
        `convert_to_timedelta` function).
        """
        if not hasattr(self, "_interval"):
            self._interval = 10000 # Default is every 10 seconds
        return self._interval 
開發者ID:Wramberg,項目名稱:TerminalView,代碼行數:12,代碼來源:terminal.py

示例10: __init__

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import timedelta [as 別名]
def __init__(self, name, offset):
        self._name = name

        try:
            # Allow a timedelta
            offset = offset.total_seconds()
        except (TypeError, AttributeError):
            pass
        self._offset = datetime.timedelta(seconds=offset) 
開發者ID:MediaBrowser,項目名稱:plugin.video.emby,代碼行數:11,代碼來源:tz.py

示例11: fromutc

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import timedelta [as 別名]
def fromutc(self, dt):
        """
        The ``tzfile`` implementation of :py:func:`datetime.tzinfo.fromutc`.

        :param dt:
            A :py:class:`datetime.datetime` object.

        :raises TypeError:
            Raised if ``dt`` is not a :py:class:`datetime.datetime` object.

        :raises ValueError:
            Raised if this is called with a ``dt`` which does not have this
            ``tzinfo`` attached.

        :return:
            Returns a :py:class:`datetime.datetime` object representing the
            wall time in ``self``'s time zone.
        """
        # These isinstance checks are in datetime.tzinfo, so we'll preserve
        # them, even if we don't care about duck typing.
        if not isinstance(dt, datetime.datetime):
            raise TypeError("fromutc() requires a datetime argument")

        if dt.tzinfo is not self:
            raise ValueError("dt.tzinfo is not self")

        # First treat UTC as wall time and get the transition we're in.
        idx = self._find_last_transition(dt, in_utc=True)
        tti = self._get_ttinfo(idx)

        dt_out = dt + datetime.timedelta(seconds=tti.offset)

        fold = self.is_ambiguous(dt_out, idx=idx)

        return enfold(dt_out, fold=int(fold)) 
開發者ID:MediaBrowser,項目名稱:plugin.video.emby,代碼行數:37,代碼來源:tz.py

示例12: parse_date

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import timedelta [as 別名]
def parse_date(value):
    """Parse one of the following date formats into a datetime object:

    .. sourcecode:: text

        Sun, 06 Nov 1994 08:49:37 GMT  ; RFC 822, updated by RFC 1123
        Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
        Sun Nov  6 08:49:37 1994       ; ANSI C's asctime() format

    If parsing fails the return value is `None`.

    :param value: a string with a supported date format.
    :return: a :class:`datetime.datetime` object.
    """
    if value:
        t = parsedate_tz(value.strip())
        if t is not None:
            try:
                year = t[0]
                # unfortunately that function does not tell us if two digit
                # years were part of the string, or if they were prefixed
                # with two zeroes.  So what we do is to assume that 69-99
                # refer to 1900, and everything below to 2000
                if year >= 0 and year <= 68:
                    year += 2000
                elif year >= 69 and year <= 99:
                    year += 1900
                return datetime(*((year,) + t[1:7])) - timedelta(seconds=t[-1] or 0)
            except (ValueError, OverflowError):
                return None 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:32,代碼來源:http.py

示例13: test_repr

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import timedelta [as 別名]
def test_repr(self):
        assert repr(self.offset) == '<BusinessDay>'
        assert repr(self.offset2) == '<2 * BusinessDays>'

        if compat.PY37:
            expected = '<BusinessDay: offset=datetime.timedelta(days=1)>'
        else:
            expected = '<BusinessDay: offset=datetime.timedelta(1)>'
        assert repr(self.offset + timedelta(1)) == expected 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:11,代碼來源:test_offsets.py

示例14: test_with_offset

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import timedelta [as 別名]
def test_with_offset(self):
        offset = self.offset + timedelta(hours=2)

        assert (self.d + offset) == datetime(2008, 1, 2, 2) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:6,代碼來源:test_offsets.py

示例15: test_offset

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import timedelta [as 別名]
def test_offset(self):
        # Saturday
        last_sat = datetime(2013, 8, 31)
        next_sat = datetime(2013, 9, 28)
        offset_sat = LastWeekOfMonth(n=1, weekday=5)

        one_day_before = (last_sat + timedelta(days=-1))
        assert one_day_before + offset_sat == last_sat

        one_day_after = (last_sat + timedelta(days=+1))
        assert one_day_after + offset_sat == next_sat

        # Test On that day
        assert last_sat + offset_sat == next_sat

        # Thursday

        offset_thur = LastWeekOfMonth(n=1, weekday=3)
        last_thurs = datetime(2013, 1, 31)
        next_thurs = datetime(2013, 2, 28)

        one_day_before = last_thurs + timedelta(days=-1)
        assert one_day_before + offset_thur == last_thurs

        one_day_after = last_thurs + timedelta(days=+1)
        assert one_day_after + offset_thur == next_thurs

        # Test on that day
        assert last_thurs + offset_thur == next_thurs

        three_before = last_thurs + timedelta(days=-3)
        assert three_before + offset_thur == last_thurs

        two_after = last_thurs + timedelta(days=+2)
        assert two_after + offset_thur == next_thurs

        offset_sunday = LastWeekOfMonth(n=1, weekday=WeekDay.SUN)
        assert datetime(2013, 7, 31) + offset_sunday == datetime(2013, 8, 25) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:40,代碼來源:test_offsets.py


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