benlev
benlev

Reputation: 120

Convert TimedeltaIndex to DatetimeIndex

I'm trying to extract times from a TimedeltaIndex object. I tried using pd.to_datetime() but got the following error:

>>> import pandas as pd
>>> times = pd.timedelta_range(start='10:00:00', end='12:00:00', freq='min')
>>> pd.to_datetime(times)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File ".../python3.6/site-packages/pandas/core/tools/datetimes.py", line 812, in to_datetime
    result = convert_listlike(arg, format, name=arg.name)
  File ".../python3.6/site-packages/pandas/core/tools/datetimes.py", line 371, in _convert_listlike_datetimes
    arg, _ = maybe_convert_dtype(arg, copy=False)
  File ".../python3.6/site-packages/pandas/core/arrays/datetimes.py", line 2123, in maybe_convert_dtype
    raise TypeError(f"dtype {data.dtype} cannot be converted to datetime64[ns]")
TypeError: dtype timedelta64[ns] cannot be converted to datetime64[ns]

I ended up using the following line but I am hoping there is a more elegant solution: (pd.to_datetime(0) + times).time

Upvotes: 4

Views: 1143

Answers (1)

hasanyaman
hasanyaman

Reputation: 328

You can convert TimeDeltaIndex to datetime by first converting it to integer.

import pandas as pd
import numpy as np

times = pd.timedelta_range(start='10:00:00', end='12:00:00', freq='min')
pd.to_datetime(times.astype(np.int64)).time

This gives the same output as the (pd.to_datetime(0) + times).time

Upvotes: 2

Related Questions