8000 Add num2timedelta method with test by dstansby · Pull Request #8870 · matplotlib/matplotlib · GitHub
[go: up one dir, main page]

Skip to content

Add num2timedelta method with test #8870

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Aug 7, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 33 additions & 1 deletion lib/matplotlib/dates.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@
import matplotlib.ticker as ticker


__all__ = ('date2num', 'num2date', 'drange', 'epoch2num',
__all__ = ('date2num', 'num2date', 'num2timedelta', 'drange', 'epoch2num',
'num2epoch', 'mx2num', 'DateFormatter',
'IndexDateFormatter', 'AutoDateFormatter', 'DateLocator',
'RRuleLocator', 'AutoDateLocator', 'YearLocator',
Expand Down Expand Up @@ -406,6 +406,38 @@ def num2date(x, tz=None):
return _from_ordinalf_np_vectorized(x, tz).tolist()


def _ordinalf_to_timedelta(x):
return datetime.timedelta(days=x)


_ordinalf_to_timedelta_np_vectorized = np.vectorize(_ordinalf_to_timedelta)


def num2timedelta(x):
"""
Converts number of days to a :class:`timdelta` object.
If *x* is a sequence, a sequence of :class:`timedelta` objects will
be returned.

Parameters
----------
x : float, sequence of floats
Number of days (fraction part represents hours, minutes, seconds)

Returns
-------
:class:`timedelta` or list[:class:`timedelta`]

"""
if not cbook.iterable(x):
return _ordinalf_to_timedelta(x)
else:
x = np.asarray(x)
if not x.size:
return x
return _ordinalf_to_timedelta_np_vectorized(x).tolist()


def drange(dstart, dend, delta):
"""
Return a date range as float Gregorian ordinals. *dstart* and
Expand Down
9 changes: 9 additions & 0 deletions lib/matplotlib/tests/test_dates.py
Original file line number Diff line number Diff line change
Expand Up @@ -457,3 +457,12 @@ def test_DayLocator():
def test_tz_utc():
dt = datetime.datetime(1970, 1, 1, tzinfo=mdates.UTC)
dt.tzname()


@pytest.mark.parametrize("x, tdelta",
[(1, datetime.timedelta(days=1)),
([1, 1.5], [datetime.timedelta(days=1),
datetime.timedelta(days=1.5)])])
def test_num2timedelta(x, tdelta):
dt = mdates.num2timedelta(x)
assert dt == tdelta
0