Python Pandas - 返回 DatetimeIndex 作为 datetime.datetime 对象的对象 ndarray
若要将 DatetimeIndex 作为 datetime.datetime 对象的对象 ndarray 返回,请使用 datetimeindex.to_pydatetime() 方法。
首先,导入所需的库 −
import pandas as pd
创建具有周期 5 和频率为 Y(即年)的 DatetimeIndex −
datetimeindex = pd.date_range('2021-10-18 07:20:32.261811624', periods=5, freq='2Y')
显示 DateTimeIndex −
print("DateTimeIndex...\n", datetimeindex)
将 DatetimeIndex 作为对象 ndarray 返回 −
print("\nReturn DatetimeIndex as object ndarray of datetime.datetime objects...\n", datetimeindex.to_pydatetime())
示例
以下是代码 −
import pandas as pd # DatetimeIndex with period 5 and frequency as Y i.e. year datetimeindex = pd.date_range('2021-10-18 07:20:32.261811624', periods=5, freq='2Y') # display DateTimeIndex print("DateTimeIndex...\n", datetimeindex) # display DateTimeIndex frequency print("DateTimeIndex frequency...\n", datetimeindex.freq) # Return DatetimeIndex as object ndarray print("\nReturn DatetimeIndex as object ndarray of datetime.datetime objects...\n", datetimeindex.to_pydatetime())
输出
以下代码会生成以下结果 −
DateTimeIndex... DatetimeIndex(['2021-12-31 07:20:32.261811624', '2023-12-31 07:20:32.261811624', '2025-12-31 07:20:32.261811624', '2027-12-31 07:20:32.261811624', '2029-12-31 07:20:32.261811624'], dtype='datetime64[ns]', freq='2A-DEC') DateTimeIndex frequency... <2 * YearEnds: month=12> Return DatetimeIndex as object ndarray of datetime.datetime objects... [datetime.datetime(2021, 12, 31, 7, 20, 32, 261811) datetime.datetime(2023, 12, 31, 7, 20, 32, 261811) datetime.datetime(2025, 12, 31, 7, 20, 32, 261811) datetime.datetime(2027, 12, 31, 7, 20, 32, 261811) datetime.datetime(2029, 12, 31, 7, 20, 32, 261811)]
广告