Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python Pandas - สร้าง DateTime ด้วย DateTimeIndex

บทนำ

ใช้ pd.date_range() เพื่อสร้าง DateTimeIndex พร้อมกำหนด periods, timezone และ frequency

ขั้นตอน

1. นำเข้าไลบรารี

import pandas as pd

2. สร้าง DateTimeIndex ความถี่รายเดือน 8 ช่วง

datetime = pd.date_range('2021-09-24 02:35:55', periods=8, tz='Australia/Sydney', freq='M')

3. แสดงผลและดึงส่วนประกอบต่างๆ

print("DateTime...\n", datetime)
print("\nGetting the day name..\n", datetime.day_name())
print("\nGetting the month name..\n", datetime.month_name())
print("\nGetting the year name..\n", datetime.year)
print("\nGetting the hour..\n", datetime.hour)
print("\nGetting the minutes..\n", datetime.minute)
print("\nGetting the seconds..\n", datetime.second)

ตัวอย่างโค้ดเต็ม

import pandas as pd

datetime = pd.date_range('2021-09-24 02:35:55', periods=8, tz='Australia/Sydney', freq='M')

print("DateTime...\n", datetime)
print("\nGetting the day name..\n", datetime.day_name())
print("\nGetting the month name..\n", datetime.month_name())
print("\nGetting the year name..\n", datetime.year)
print("\nGetting the hour..\n", datetime.hour)
print("\nGetting the minutes..\n", datetime.minute)
print("\nGetting the seconds..\n", datetime.second)

ผลลัพธ์

DateTime...
DatetimeIndex(['2021-09-30 02:35:55+10:00', '2021-10-31 02:35:55+11:00',
               '2021-11-30 02:35:55+11:00', '2021-12-31 02:35:55+11:00',
               '2022-01-31 02:35:55+11:00', '2022-02-28 02:35:55+11:00',
               '2022-03-31 02:35:55+11:00', '2022-04-30 02:35:55+10:00'],
              dtype='datetime64[ns, Australia/Sydney]', freq='M')

Getting the day name..
Index(['Thursday', 'Sunday', 'Tuesday', 'Friday', 'Monday', 'Monday', 'Thursday', 'Saturday'], dtype='object')

Getting the month name..
Index(['September', 'October', 'November', 'December', 'January', 'February', 'March', 'April'], dtype='object')

Getting the year name..
Int64Index([2021, 2021, 2021, 2021, 2022, 2022, 2022, 2022], dtype='int64')

Getting the hour..
Int64Index([2, 2, 2, 2, 2, 2, 2, 2], dtype='int64')

Getting the minutes..
Int64Index([35, 35, 35, 35, 35, 35, 35, 35], dtype='int64')

Getting the seconds..
Int64Index([55, 55, 55, 55, 55, 55, 55, 55], dtype='int64')

คำอธิบาย

  • .day_name(), .month_name() คืนค่า Index แบบ string
  • .year, .hour, .minute, .second คืนค่า Int64Index
  • เขตเวลา Australia/Sydney มี DST ทำให้ offset เปลี่ยนจาก +10:00 เป็น +11:00