หากต้องการแปลง DateTimeIndex ให้เป็น ndarray ของ datetime.datetime objects (มาตรฐาน Python) สามารถใช้เมธอด datetimeindex.to_pydatetime()
ขั้นตอนการทำงาน
1. นำเข้าไลบรารีที่จำเป็น
import pandas as pd
2. สร้าง DatetimeIndex ด้วยความถี่เป็นปี
datetimeindex = pd.date_range(
'2021-10-18 07:20:32.261811624',
periods=5,
freq='2Y'
)
3. แสดง DateTimeIndex
print("DateTimeIndex...\n", datetimeindex)
4. แปลงเป็น ndarray ของ datetime.datetime
print("\nDateTimeIndex เป็น ndarray ของ datetime.datetime...\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'
)
# แสดง DateTimeIndex
print("DateTimeIndex...\n", datetimeindex)
# แสดง DateTimeIndex frequency
print("DateTimeIndex frequency...\n", datetimeindex.freq)
# แปลง DateTimeIndex เป็น object ndarray
print("\nDateTimeIndex เป็น ndarray ของ datetime.datetime...\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>
DateTimeIndex เป็น ndarray ของ datetime.datetime...
[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)]
คำอธิบาย:
freq='2Y'หมายถึง ทุก 2 ปี (Year End frequency)- Pandas ปรับวันที่ให้อยู่ที่สิ้นปี (Year End) → 31 ธันวาคม
to_pydatetime()คืนค่า NumPy ndarray dtype=object แต่ละตัวเป็นdatetime.datetimeมาตรฐาน- มีประโยชน์เมื่อต้องส่งต่อให้ไลบรารีที่ไม่รองรับ pandas Timestamp (เช่น matplotlib แบบเก่า, บาง ORM)
ความแตกต่าง: to_pydatetime() vs to_numpy()
# to_pydatetime(): คืน datetime.datetime objects
arr1 = datetimeindex.to_pydatetime()
print(type(arr1[0])) #
# to_numpy(): คืน numpy.datetime64 (default)
arr2 = datetimeindex.to_numpy()
print(type(arr2[0])) #
# to_numpy(dtype=object): คืน Timestamp objects
arr3 = datetimeindex.to_numpy(dtype=object)
print(type(arr3[0])) #