Pandas Series.dt.day Property
Series.dt.dayis a Pandas attribute used toextract the day (date) from date-time. It is part of the dt accessor and can quickly extract the day of the month (1-31) from a datetime Series.
In time series data analysis, analyzing by day is a common requirement, such as analyzing specific days of each month, identifying periodic patterns, etc.dt.dayThis attribute makes such operations simple and efficient.
Word Definition: dayIt means "day", i.e., returns the day in a date (the day of the month).
Basic Syntax and Parameters
Series.dt.dayIt is an attribute of the Series dt accessor, used to extract the day.
Syntax Format
Series.dt.day
Parameter Description
This attribute does not require any parameters; it directly accesses the day information of the datetime Series.
Return Value Description
- Return valueReturns an integer Series containing the day (1-31).
- EffectExtracts the day part of dates from a datetime64 Series, returning integers from 1 to 31.
Example
Let us thoroughly master, through a series of examples from simple to complex,Series.dt.daythe usage of this property.
Example 1: Basic Usage - Extract Day
Example
# 1. Create a datetime Series
print("=== Create datetime Series ===")
dates = pd.Series([
'2023-01-15',
'2023-02-20',
'2023-03-05',
'2023-04-30',
'2023-05-25',
'2023-12-31'
])
# Convert to datetime type
datetime_series = pd.to_datetime(dates)
print("Original date:")
print(datetime_series)
# 2. Use dt.day to extract the day
print("\n=== Use dt.day to extract the day ===")
days = datetime_series.dt.day
print("Day:")
print(days)
# 3. Extract year, month, and day simultaneously
print("\n=== Extract year, month, and day simultaneously ===")
datetime_series = pd.to_datetime(dates)
df = pd.DataFrame({
'Original date': datetime_series,
'Year': datetime_series.dt.year,
'Month': datetime_series.dt.month,
'Day': datetime_series.dt.day
})
print(df)
# 4. View how many days are in each month
print("\n=== Number of days in each month ===")
dates_full = pd.date_range('2023-01-01', periods=12, freq='MS')
days_in_month = dates_full.dt.days_in_month
print(pd.DataFrame({
'Month': dates_full,
'Number of days': days_in_month
}))
# 5. Number of days in February in a leap year
print("\n=== Number of days in February in a leap year ===")
leap_feb = pd.Timestamp('2024-02-01').days_in_month
print(f"Days in February 2024: {leap_feb}")
non_leap_feb = pd.Timestamp('2023-02-01').days_in_month
print(f"Days in February 2023: {non_leap_feb}")
Output:
=== 创建日期时间 Series ===
0 2023-01-15
1 2023-02-20
2 2023-03-05
3 2023-04-30
4 2023-05-25
5 2023-12-31
dtype: datetime64[ns]
=== 使用 dt.day 提取天 ===
天:
0 15
1 20
2 5
3 30
4 25
5 31
dtype: int64
=== 同时提取年月日 ===
原始日期 年 月 日
0 2023-01-15 2023 1 15
1 2023-02-20 2023 2 20
2 2023-03-05 2023 3 5
3 2023-04-30 2023 4 30
4 2023-05-25 2023 5 25
5 2023-12-31 2023 12 31
=== 各月的天数 ===
月份 天数
0 2023-01-01 31
1 2023-02-01 28
2 2023-03-01 31
3 2023-04-01 30
4 2023-05-01 31
5 2023-06-01 30
6 2023-07-01 31
7 2023-08-01 31
8 2023-09-01 30
9 2023-10-01 31
10 2023-11-01 30
11 2023-12-01 31
=== 闰年2月天数 ===
2024年2月天数: 29
2023年2月天数: 28
Code Analysis:
dt.dayReturns integers from 1 to 31, representing the day of the month.- You can extract year, month, and day simultaneously to create a new DataFrame.
days_in_monthThis attribute can get the number of days in each month, which is very useful for handling month-end dates.- 2024 is a leap year, February has 29 days; 2023 is a common year, February has 28 days.
Example 2: Filtering and Analysis by Day
Example
import numpy as np
# Create a dataset containing dates
print("=== Create transaction data ===")
np.random.seed(100)
# Generate 30 days of data
dates = pd.date_range('2023-03-01', periods=30, freq='D')
df = pd.DataFrame({
'date': dates,
'transactions': np.random.randint(50, 200, 30),
'revenue': np.random.randint(5000, 20000, 30)
})
# Extract the day
df['day'] = df['date'].dt.day
print(df.head(15))
# Filter records for a specific day (e.g., the 15th of each month)
print("\n=== Transactions on the 15th of each month ===")
day_15 = df[df['day'] == 15]
print(day_15)
# Filter first half and second half of the month
print("\n=== First half vs Second half ===")
df['half'] = df['day'].apply(lambda x: 'First half' if x <= 15 else 'Second half')
half_stats = df.groupby('half')['transactions'].agg(['sum', 'mean']).round(2)
half_stats.columns = ['Total transactions', 'Average transactions']
print(half_stats)
# Statistics by day
print("\n=== Average revenue by day ===")
daily_avg = df.groupby('day')['revenue'].mean().round(2)
print(daily_avg)
# Find the day with the highest revenue
print("\n=== Days with highest and lowest revenue ===")
max_day = df.loc[df['revenue'].idxmax()]
min_day = df.loc[df['revenue'].idxmin()]
print(f"Highest revenue: {max_day['date'].date()}, amount {max_day['revenue']}")
print(f"Lowest revenue: {min_day['date'].date()}, amount {min_day['revenue']}")
Output:
=== 创建交易数据 ===
date transactions revenue day
0 2023-03-01 73 16200 1
1 2023-03-02 163 18800 2
2 2023-03-03 76 9600 3
3 2023-03-04 83 10500 4
4 2023-03-05 136 16200 5
5 2023-03-06 86 11700 6
6 2023-03-07 87 13400 7
7 2023-03-08 168 14200 8
8 2023-03-09 163 15800 9
9 2023-03-10 82 11000 10
10 2023-03-11 106 14600 11
11 2023-03-12 152 15900 12
12 2023-03-13 数据截断...
=== 每月15号的交易 ===
date transactions revenue day
14 2023-03-15 104 12900 15
=== 上半月 vs 下半月 ===
总交易数 平均交易数
下半月 2117 111.42
上半月 1873 117.06
=== 按天统计平均收入 ===
day
1 16200.00
2 18800.00
...
=== 收入最高和最低的天 ===
最高收入: 2023-03-02,金额 18800
最低收入: 2023-03-03,金额 9600
Code Analysis:
- You can filter and perform group analysis by day.
- You can divide days into the first half and second half of the month for analysis.
idxmax()andidxmin()You can quickly find the records corresponding to the maximum and minimum values.
Example 3: Month-End Date Handling
Example
# 1. Handle the last day of different months
print("=== Last day of each month ===")
dates = pd.date_range('2023-01-01', periods=12, freq='MS')
print("First day of each month:")
print(dates)
# Get the last day of each month
last_days = dates + pd.offsets.MonthEnd(0)
print("\nLast day of each month:")
print(last_days)
# 2. Determine whether it is the end of the month
print("\n=== Determine whether it is the end of the month ===")
test_dates = pd.Series([
'2023-01-30', # January 30 (not the end of the month)
'2023-01-31', # January 31 (end of the month)
'2023-02-28', # February 28 (non-leap year)
'2023-04-30', # April 30 (end of the month)
])
dt_series = pd.to_datetime(test_dates)
is_month_end = dt_series.is_month_end
result = pd.DataFrame({
'Date': dt_series,
'Is end of month': is_month_end
})
print(result)
# 3. Month-start date handling
print("\n=== Determine whether it is the start of the month ===")
is_month_start = dt_series.is_month_start
result['Is start of month'] = is_month_start
print(result)
# 4. Handling when months have different numbers of days
print("\n=== Handling months with different numbers of days ===")
dates_to_check = pd.Series([
'2023-01-31', # Valid date
'2023-02-30', # Invalid date (February has no 30th)
])
# Try to convert and handle invalid dates
try:
valid_dates = pd.to_datetime(dates_to_check, errors='coerce')
print("Converted date:")
print(valid_dates)
print("\nDay corresponding to each date:")
print(valid_dates.dt.day)
except Exception as e:
print(f"Error: {e}")
Output:
=== 各月最后一天 ===
每月第一天:
DatetimeIndex(['2023-01-01', '2023-02-01', '2023-03-01', '2023-04-01',
'2023-05-01', '2023-06-01', '2023-07-01', '2023-03-01',
'2023-09-01', '2023-10-01', '2023-11-01', '2023-12-01'],
dtype='datetime64[ns]', freq=None)
每月最后一天:
DatetimeIndex(['2023-01-31', '2023-02-28', '2023-03-31', '2023-04-30',
'2023-05-31', '2023-06-30', '2023-07-31', '2023-03-31',
'2023-09-30', '2023-10-31', '2023-11-30', '2023-12-31'],
dtype='datetime64[ns]', freq=None)
=== 判断是否为月末 ===
日期 是否为月末
0 2023-01-30 False
1 2023-01-31 True
2 2023-02-28 True
3 2023-04-30 True
=== 判断是否为月初 ===
日期 是否为月末 是否为月初
0 2023-01-30 False False
1 2023-01-31 False False
2 2023-02-28 False False
3 2023-04-30 False False
=== 月份天数不一致的处理 ===
转换后的日期:
0 2023-01-31
1 NaT
Name: date, dtype: datetime64[ns]
各日期对应的天:
0 31.0
1 NaN
Code Analysis:
is_month_endThis attribute can determine whether it is the end of the month.is_month_startThis attribute can determine whether it is the start of the month.pd.offsets.MonthEnd(0)You can get the last day of the month.- When handling invalid dates, you can use
errors='coerce'to convert invalid dates to NaT.
Notes
Important Notes:
Series.dt.dayIt can only be used on Series of datetime64 type.- The returned day range is 1-31; the exact maximum depends on the month (February has a maximum of 28/29 days, April/June/September/November have 30 days, and other months have 31 days).
- You can use
dt.days_in_monthto get the number of days in each month.- When handling data containing missing values (NaT),
dt.dayNaT will be returned at the corresponding position.
Other Extensions
Pandas Common Functions