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

Python Pandas - Trích xuất ngày thứ bao nhiêu trong năm từ DateTimeIndex


Để lấy ngày thứ bao nhiêu trong năm (1-366) từ DateTimeIndex, sử dụng thuộc tính DateTimeIndex.dayofyear.

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

1. Import thư viện

import pandas as pd

2. Tạo DateTimeIndex

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

3. Hiển thị DateTimeIndex

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

4. Lấy ngày trong năm

print("\nNgày thứ trong năm...\n", datetimeindex.dayofyear)

Ví dụ hoàn chỉnh

import pandas as pd

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

print("DateTimeIndex...\n", datetimeindex)
print("Tần suất...\n", datetimeindex.freq)
print("\nNgày thứ trong năm...\n", datetimeindex.dayofyear)

Kết quả đầu ra

DateTimeIndex...
DatetimeIndex(['2021-10-20 02:30:50+11:00', '2021-10-21 02:30:50+11:00',
               '2021-10-22 02:30:50+11:00', '2021-10-23 02:30:50+11:00',
               '2021-10-24 02:30:50+11:00', '2021-10-25 02:30:50+11:00'],
              dtype='datetime64[ns, Australia/Sydney]', freq='D')
Tần suất...
<Day>
Ngày thứ trong năm...
Int64Index([293, 294, 295, 296, 297, 298], dtype='int64')

Giải thích: 20/10 là ngày thứ 293 của năm 2021 (không năm nhuận), 21/10 là 294, ..., 25/10 là 298.