Python Pandas - 将 DatetimeIndex 作为 datetime.datetime 对象的对象 ndarray 返回
要将DatetimeIndex作为对象的对象ndarray返回datetime.datetime,请使用该方法。datetimeindex.to_pydatetime()
首先,导入所需的库-
import pandas as pd
创建一个日期时间索引,周期为5,频率为Y,即年份-
datetimeindex = pd.date_range('2021-10-18 07:20:32.261811624', periods=5, freq='2Y')
显示日期时间索引-
print("DateTimeIndex...\n", datetimeindex)
将DatetimeIndex作为对象ndarray返回-
print("\nReturn DatetimeIndex as object ndarray ofdatetime.datetimeobjects...\n", datetimeindex.to_pydatetime())
示例
以下是代码-
import pandas as pd #DatetimeIndex,周期为5,频率为Y,即年份 datetimeindex = pd.date_range('2021-10-18 07:20:32.261811624', periods=5, freq='2Y') #显示日期时间索引 print("DateTimeIndex...\n", datetimeindex) #显示日期时间索引 frequency print("DateTimeIndex frequency...\n", datetimeindex.freq) #将DatetimeIndex作为对象ndarray返回 print("\nReturn DatetimeIndex as object ndarray ofdatetime.datetimeobjects...\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 ofdatetime.datetimeobjects... [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)]