Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Python Pandas - Trích xuất ngày từ DateTimeIndex

Để trích xuất ngày trong tháng từ DateTimeIndex, sử dụng thuộc tính DateTimeIndex.day.

Các bước thực hiện

1. Import thư viện

import pandas as pd

2. Tạo DateTimeIndex (tần suất ngày)

datetimeindex = pd.date_range(
    '2021-10-20 02:35:55',
    periods=6,
    tz='Australia/Sydney',
    freq='D'
)

3. Hiển thị DateTimeIndex

print("DateTimeIndex...\n", datetimeindex)

4. Trích xuất ngày

print("\nNgày trong tháng...\n", datetimeindex.day)

Ví dụ hoàn chỉnh

import pandas as pd

datetimeindex = pd.date_range(
    '2021-10-20 02:35:55',
    periods=6,
    tz='Australia/Sydney',
    freq='D'
)

print("DateTimeIndex...\n", datetimeindex)
print("DateTimeIndex frequency...\n", datetimeindex.freq)
print("\nNgày trong tháng...\n", datetimeindex.day)

Kết quả đầu ra

DateTimeIndex...
DatetimeIndex(['2021-10-20 02:35:55+11:00', '2021-10-21 02:35:55+11:00',
               '2021-10-22 02:35:55+11:00', '2021-10-23 02:35:55+11:00',
               '2021-10-24 02:35:55+11:00', '2021-10-25 02:35:55+11:00'],
              dtype='datetime64[ns, Australia/Sydney]', freq='D')

DateTimeIndex frequency...


Ngày trong tháng...
Int64Index([20, 21, 22, 23, 24, 25], dtype='int64')

Các thuộc tính trích xuất thời gian thường dùng

Thuộc tínhÝ nghĩaKết quả ví dụ
.yearNăm2021
.monthTháng (1-12)10
.dayNgày trong tháng (1-31)20
.hourGiờ (0-23)2
.minutePhút (0-59)35
.secondGiây (0-59)55
.microsecondMicro-giây (0-999999)0
.nanosecondNano-giây (0-999)0
.dayofweekThứ trong tuần (0=Thứ 2)2 (Thứ 4)
.dayofyearNgày trong năm (1-366)293
.weekTuần trong năm42
.quarterQuý (1-4)4

Lưu ý: Tất cả trả về Int64Index (mảng số nguyên 64-bit).