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

In số ngày trong tháng từ Series ngày tháng Python

Mô tả bài toán

Cho một date series, cần tìm số ngày của tháng chứa ngày đó. Ví dụ: ngày 2020-02-10 (tháng 2 năm 2020 - năm nhuận) có 29 ngày.

Giải pháp

Sử dụng pd.date_range() tạo DatetimeIndex, chuyển thành Series, sau đó truy cập thuộc tính .dt.daysinmonth.

Ví dụ code hoàn chỉnh

import pandas as pd

# Tạo date range 1 kỳ bắt đầu từ 2020-02-10
date = pd.date_range('2020-02-10', periods=1)
data = pd.Series(date)
print("Series ngày:")
print(data)

# Lấy số ngày trong tháng
days_in_month = data.dt.daysinmonth
print("\nSố ngày trong tháng:")
print(days_in_month)

Đầu ra

Series ngày:
0   2020-02-10
dtype: datetime64[ns]

Số ngày trong tháng:
0    29
dtype: int64

Mở rộng: Áp dụng cho nhiều ngày

import pandas as pd

# Nhiều ngày khác tháng
dates = pd.date_range('2023-01-15', periods=5, freq='MS')  # 5 tháng đầu năm 2023
data = pd.Series(dates)
print(data.dt.daysinmonth)
0    31
1    28
2    31
3    30
4    31
dtype: int64

Thuộc tính hữu ích khác: .dt.day, .dt.month, .dt.year, .dt.quarter, .dt.is_leap_year.