บทนำ
ใช้ DateTimeIndex.floor() พร้อม freq='S' เพื่อปัดลงเป็นหน่วยวินาที
ขั้นตอน
1. นำเข้าไลบรารี
import pandas as pd
2. สร้าง DateTimeIndex
datetimeindex = pd.date_range('2021-10-18 07:20:32.261811624', periods=5, tz='Australia/Adelaide', freq='40S')
3. แสดงข้อมูลและดำเนินการ Floor
print("DateTimeIndex...\n", datetimeindex)
print("DateTimeIndex frequency...\n", datetimeindex.freq)
# getting the second
res = datetimeindex.second
print("\nThe seconds from DateTimeIndex...\n", res)
print("\nPerforming floor operation with seconds frequency...\n", datetimeindex.floor(freq='S'))
ตัวอย่างโค้ดเต็ม
import pandas as pd
datetimeindex = pd.date_range('2021-10-18 07:20:32.261811624', periods=5, tz='Australia/Adelaide', freq='40S')
print("DateTimeIndex...\n", datetimeindex)
print("DateTimeIndex frequency...\n", datetimeindex.freq)
res = datetimeindex.second
print("\nThe seconds from DateTimeIndex...\n", res)
print("\nPerforming floor operation with seconds frequency...\n", datetimeindex.floor(freq='S'))
ผลลัพธ์
DateTimeIndex...
DatetimeIndex(['2021-10-18 07:20:32.261811624+10:30', '2021-10-18 07:21:12.261811624+10:30',
'2021-10-18 07:21:52.261811624+10:30', '2021-10-18 07:22:32.261811624+10:30',
'2021-10-18 07:23:12.261811624+10:30'],
dtype='datetime64[ns, Australia/Adelaide]', freq='40S')
DateTimeIndex frequency...
<40 * Seconds>
The seconds from DateTimeIndex...
Int64Index([32, 12, 52, 32, 12], dtype='int64')
Performing floor operation with seconds frequency...
DatetimeIndex(['2021-10-18 07:20:32+10:30', '2021-10-18 07:21:12+10:30',
'2021-10-18 07:21:52+10:30', '2021-10-18 07:22:32+10:30',
'2021-10-18 07:23:12+10:30'],
dtype='datetime64[ns, Australia/Adelaide]', freq=None)
คำอธิบาย
ส่วนทศนิยมของวินาทีถูกตัดทิ้ง: 32.261811624 → 32, 12.261811624 → 12 ไมโครวินาทีและนานโววินาทีกลายเป็นศูนย์