[英]Convert TimedeltaIndex to DatetimeIndex
I'm trying to extract times from a TimedeltaIndex object.我正在尝试从 TimedeltaIndex object 中提取时间。 I tried using
pd.to_datetime()
but got the following error:我尝试使用
pd.to_datetime()
但收到以下错误:
>>> 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
我最终使用了以下行,但我希望有一个更优雅的解决方案:
(pd.to_datetime(0) + times).time
You can convert TimeDeltaIndex to datetime by first converting it to integer.您可以通过首先将 TimeDeltaIndex 转换为 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这给出了与(pd.to_datetime(0) + times).time 相同的 output
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.