ในการแปลงการประทับเวลาที่กำหนดเป็นช่วงเวลา ให้ใช้ timestamp.to_period() กระบวนการ. ภายในนั้น ตั้งค่าความถี่โดยใช้ ความถี่ พารามิเตอร์. สำหรับความถี่รายเดือน ให้ตั้งความถี่เป็น M
ขั้นแรก นำเข้าไลบรารีที่จำเป็น -
import pandas as pd
ตั้งค่าวัตถุประทับเวลาใน Pandas
timestamp = pd.Timestamp(2021, 9, 18, 11, 50, 20, 33)
แปลงการประทับเวลาเป็นช่วงเวลา เราได้ตั้งค่าความถี่เป็นรายเดือนโดยใช้พารามิเตอร์ "ความถี่" ที่มีค่า 'M'
timestamp.to_period(freq='M')
ตัวอย่าง
ต่อไปนี้เป็นรหัส
import pandas as pd
# set the timestamp object in Pandas
timestamp = pd.Timestamp(2021, 9, 18, 11, 50, 20, 33)
# display the Timestamp
print("Timestamp...\n", timestamp)
# convert timestamp to Period
# we have set the frequency as monthly using the "freq" parameter with value 'M'
print("\nTimestamp to Period with monthly frequency...\n", timestamp.to_period(freq='M')) ผลลัพธ์
ซึ่งจะได้รหัสดังต่อไปนี้
Timestamp... 2021-09-18 11:50:20.000033 Timestamp to Period with monthly frequency... 2021-09