Python datetime.datetime.timedelta() Examples

The following are 30 code examples of datetime.datetime.timedelta(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module datetime.datetime , or try the search function .
Example #1
Source File: test_license.py    From pywr with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #2
Source File: http.py    From lambda-packs with MIT License 6 votes vote down vote up
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 
Example #3
Source File: http.py    From lambda-packs with MIT License 6 votes vote down vote up
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) 
Example #4
Source File: utils.py    From azure-uamqp-python with MIT License 6 votes vote down vote up
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) 
Example #5
Source File: timeutils.py    From typhon with MIT License 6 votes vote down vote up
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 
Example #6
Source File: http.py    From recruit with Apache License 2.0 6 votes vote down vote up
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) 
Example #7
Source File: http.py    From recruit with Apache License 2.0 6 votes vote down vote up
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 
Example #8
Source File: _common.py    From faces with GNU General Public License v2.0 5 votes vote down vote up
def _total_seconds(td):
    # Python 2.6 doesn't have a total_seconds() method on timedelta objects
    return ((td.seconds + td.days * 86400) * 1000000 +
            td.microseconds) // 1000000 
Example #9
Source File: tzinfo.py    From faces with GNU General Public License v2.0 5 votes vote down vote up
def _to_seconds(td):
    '''Convert a timedelta to seconds'''
    return td.seconds + td.days * 24 * 60 * 60 
Example #10
Source File: test_offsets.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def test_with_offset(self):
        offset = self.offset + timedelta(hours=2)

        assert (self.d + offset) == datetime(2008, 1, 2, 2) 
Example #11
Source File: tz.py    From vnpy_crypto with MIT License 5 votes vote down vote up
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)) 
Example #12
Source File: tz.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def __init__(self):
        super(tzlocal, self).__init__()

        self._std_offset = datetime.timedelta(seconds=-time.timezone)
        if time.daylight:
            self._dst_offset = datetime.timedelta(seconds=-time.altzone)
        else:
            self._dst_offset = self._std_offset

        self._dst_saved = self._dst_offset - self._std_offset
        self._hasdst = bool(self._dst_saved)
        self._tznames = tuple(time.tzname) 
Example #13
Source File: test_datetime.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def test_indexing_over_size_cutoff():
    import datetime
    # #1821

    old_cutoff = _index._SIZE_CUTOFF
    try:
        _index._SIZE_CUTOFF = 1000

        # create large list of non periodic datetime
        dates = []
        sec = datetime.timedelta(seconds=1)
        half_sec = datetime.timedelta(microseconds=500000)
        d = datetime.datetime(2011, 12, 5, 20, 30)
        n = 1100
        for i in range(n):
            dates.append(d)
            dates.append(d + sec)
            dates.append(d + sec + half_sec)
            dates.append(d + sec + sec + half_sec)
            d += 3 * sec

        # duplicate some values in the list
        duplicate_positions = np.random.randint(0, len(dates) - 1, 20)
        for p in duplicate_positions:
            dates[p + 1] = dates[p]

        df = DataFrame(np.random.randn(len(dates), 4),
                       index=dates,
                       columns=list('ABCD'))

        pos = n * 3
        timestamp = df.index[pos]
        assert timestamp in df.index

        # it works!
        df.loc[timestamp]
        assert len(df.loc[[timestamp]]) > 0
    finally:
        _index._SIZE_CUTOFF = old_cutoff 
Example #14
Source File: test_datetime.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def test_index_unique(dups):
    uniques = dups.index.unique()
    expected = DatetimeIndex([datetime(2000, 1, 2), datetime(2000, 1, 3),
                              datetime(2000, 1, 4), datetime(2000, 1, 5)])
    assert uniques.dtype == 'M8[ns]'  # sanity
    tm.assert_index_equal(uniques, expected)
    assert dups.index.nunique() == 4

    # #2563
    assert isinstance(uniques, DatetimeIndex)

    dups_local = dups.index.tz_localize('US/Eastern')
    dups_local.name = 'foo'
    result = dups_local.unique()
    expected = DatetimeIndex(expected, name='foo')
    expected = expected.tz_localize('US/Eastern')
    assert result.tz is not None
    assert result.name == 'foo'
    tm.assert_index_equal(result, expected)

    # NaT, note this is excluded
    arr = [1370745748 + t for t in range(20)] + [tslib.iNaT]
    idx = DatetimeIndex(arr * 3)
    tm.assert_index_equal(idx.unique(), DatetimeIndex(arr))
    assert idx.nunique() == 20
    assert idx.nunique(dropna=False) == 21

    arr = [Timestamp('2013-06-09 02:42:28') + timedelta(seconds=t)
           for t in range(20)] + [NaT]
    idx = DatetimeIndex(arr * 3)
    tm.assert_index_equal(idx.unique(), DatetimeIndex(arr))
    assert idx.nunique() == 20
    assert idx.nunique(dropna=False) == 21 
Example #15
Source File: test_datetime.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def test_slice_locs_indexerror():
    times = [datetime(2000, 1, 1) + timedelta(minutes=i * 10)
             for i in range(100000)]
    s = Series(lrange(100000), times)
    s.loc[datetime(1900, 1, 1):datetime(2100, 1, 1)] 
Example #16
Source File: test_offsets.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def test_validate_n_error():
    with pytest.raises(TypeError):
        DateOffset(n='Doh!')

    with pytest.raises(TypeError):
        MonthBegin(n=timedelta(1))

    with pytest.raises(TypeError):
        BDay(n=np.array([1, 2], dtype=np.int64)) 
Example #17
Source File: test_offsets.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def _test_offset(self, offset_name, offset_n, tstart, expected_utc_offset):
        offset = DateOffset(**{offset_name: offset_n})

        t = tstart + offset
        if expected_utc_offset is not None:
            assert get_utc_offset_hours(t) == expected_utc_offset

        if offset_name == 'weeks':
            # dates should match
            assert t.date() == timedelta(days=7 * offset.kwds[
                'weeks']) + tstart.date()
            # expect the same day of week, hour of day, minute, second, ...
            assert (t.dayofweek == tstart.dayofweek and
                    t.hour == tstart.hour and
                    t.minute == tstart.minute and
                    t.second == tstart.second)
        elif offset_name == 'days':
            # dates should match
            assert timedelta(offset.kwds['days']) + tstart.date() == t.date()
            # expect the same hour of day, minute, second, ...
            assert (t.hour == tstart.hour and
                    t.minute == tstart.minute and
                    t.second == tstart.second)
        elif offset_name in self.valid_date_offsets_singular:
            # expect the singular offset value to match between tstart and t
            datepart_offset = getattr(t, offset_name
                                      if offset_name != 'weekday' else
                                      'dayofweek')
            assert datepart_offset == offset.kwds[offset_name]
        else:
            # the offset should be the same as if it was done in UTC
            assert (t == (tstart.tz_convert('UTC') + offset)
                    .tz_convert('US/Pacific')) 
Example #18
Source File: test_offsets.py    From vnpy_crypto with MIT License 5 votes vote down vote up
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) 
Example #19
Source File: http.py    From lambda-packs with MIT License 5 votes vote down vote up
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 
Example #20
Source File: tzinfo.py    From faces with GNU General Public License v2.0 5 votes vote down vote up
def utcoffset(self, dt, is_dst=None):
        '''See datetime.tzinfo.utcoffset

        The is_dst parameter may be used to remove ambiguity during DST
        transitions.

        >>> from pytz import timezone
        >>> tz = timezone('America/St_Johns')
        >>> ambiguous = datetime(2009, 10, 31, 23, 30)

        >>> tz.utcoffset(ambiguous, is_dst=False)
        datetime.timedelta(-1, 73800)

        >>> tz.utcoffset(ambiguous, is_dst=True)
        datetime.timedelta(-1, 77400)

        >>> try:
        ...     tz.utcoffset(ambiguous)
        ... except AmbiguousTimeError:
        ...     print('Ambiguous')
        Ambiguous

        '''
        if dt is None:
            return None
        elif dt.tzinfo is not self:
            dt = self.localize(dt, is_dst)
            return dt.tzinfo._utcoffset
        else:
            return self._utcoffset 
Example #21
Source File: tzinfo.py    From sndlatr with Apache License 2.0 5 votes vote down vote up
def memorized_timedelta(seconds):
    '''Create only one instance of each distinct timedelta'''
    try:
        return _timedelta_cache[seconds]
    except KeyError:
        delta = timedelta(seconds=seconds)
        _timedelta_cache[seconds] = delta
        return delta 
Example #22
Source File: tzinfo.py    From faces with GNU General Public License v2.0 5 votes vote down vote up
def _to_seconds(td):
    '''Convert a timedelta to seconds'''
    return td.seconds + td.days * 24 * 60 * 60 
Example #23
Source File: tzinfo.py    From faces with GNU General Public License v2.0 5 votes vote down vote up
def memorized_datetime(seconds):
    '''Create only one instance of each distinct datetime'''
    try:
        return _datetime_cache[seconds]
    except KeyError:
        # NB. We can't just do datetime.utcfromtimestamp(seconds) as this
        # fails with negative values under Windows (Bug #90096)
        dt = _epoch + timedelta(seconds=seconds)
        _datetime_cache[seconds] = dt
        return dt 
Example #24
Source File: tzinfo.py    From faces with GNU General Public License v2.0 5 votes vote down vote up
def memorized_timedelta(seconds):
    '''Create only one instance of each distinct timedelta'''
    try:
        return _timedelta_cache[seconds]
    except KeyError:
        delta = timedelta(seconds=seconds)
        _timedelta_cache[seconds] = delta
        return delta 
Example #25
Source File: tzinfo.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def utcoffset(self, dt, is_dst=None):
        '''See datetime.tzinfo.utcoffset

        The is_dst parameter may be used to remove ambiguity during DST
        transitions.

        >>> from pytz import timezone
        >>> tz = timezone('America/St_Johns')
        >>> ambiguous = datetime(2009, 10, 31, 23, 30)

        >>> tz.utcoffset(ambiguous, is_dst=False)
        datetime.timedelta(-1, 73800)

        >>> tz.utcoffset(ambiguous, is_dst=True)
        datetime.timedelta(-1, 77400)

        >>> try:
        ...     tz.utcoffset(ambiguous)
        ... except AmbiguousTimeError:
        ...     print('Ambiguous')
        Ambiguous

        '''
        if dt is None:
            return None
        elif dt.tzinfo is not self:
            dt = self.localize(dt, is_dst)
            return dt.tzinfo._utcoffset
        else:
            return self._utcoffset 
Example #26
Source File: tzinfo.py    From sndlatr with Apache License 2.0 5 votes vote down vote up
def memorized_datetime(seconds):
    '''Create only one instance of each distinct datetime'''
    try:
        return _datetime_cache[seconds]
    except KeyError:
        # NB. We can't just do datetime.utcfromtimestamp(seconds) as this
        # fails with negative values under Windows (Bug #90096)
        dt = _epoch + timedelta(seconds=seconds)
        _datetime_cache[seconds] = dt
        return dt 
Example #27
Source File: tzinfo.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def _to_seconds(td):
    '''Convert a timedelta to seconds'''
    return td.seconds + td.days * 24 * 60 * 60 
Example #28
Source File: tzinfo.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def memorized_datetime(seconds):
    '''Create only one instance of each distinct datetime'''
    try:
        return _datetime_cache[seconds]
    except KeyError:
        # NB. We can't just do datetime.utcfromtimestamp(seconds) as this
        # fails with negative values under Windows (Bug #90096)
        dt = _epoch + timedelta(seconds=seconds)
        _datetime_cache[seconds] = dt
        return dt 
Example #29
Source File: tzinfo.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def memorized_timedelta(seconds):
    '''Create only one instance of each distinct timedelta'''
    try:
        return _timedelta_cache[seconds]
    except KeyError:
        delta = timedelta(seconds=seconds)
        _timedelta_cache[seconds] = delta
        return delta 
Example #30
Source File: tz.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def __init__(self, tzoffsetfrom, tzoffsetto, isdst,
                 tzname=None, rrule=None):
        self.tzoffsetfrom = datetime.timedelta(seconds=tzoffsetfrom)
        self.tzoffsetto = datetime.timedelta(seconds=tzoffsetto)
        self.tzoffsetdiff = self.tzoffsetto - self.tzoffsetfrom
        self.isdst = isdst
        self.tzname = tzname
        self.rrule = rrule