Pandas Series.dt.day attribute
Series.dt.day is a Pandas attribute used to **extract the day (date) from a datetime**. It is part of the dt accessor and can quickly extract the day of the month (1-31) from a Series of datetime type.
In time series data analysis, analyzing by day is a common need, such as examining specific days of each month or identifying periodic patterns.dt.day attribute makes such operations simple and efficient.
Word meaning: day means "day", that is, it returns the day in a date (the day of the month).
Basic syntax and parameters
Series.dt.day is an attribute of the dt accessor of Series, used to extract the day.
Syntax format
Series.dt.day
Parameter Description
This attribute requires no arguments; simply access the day information of a datetime Series.
Return value description
- Return Value: Returns an integer Series containing the days (1-31).
- effect: Extracts the day portion from a Series of datetime64 type, returning integers from 1 to 31.
Example
Let us thoroughly master Series.dt.day through a series of examples from simple to complex.
Example 1: Basic usage - extracting the day
Example
import
pandas
as
pd
1. Create a Series of datetimes
(
"=== Create a 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
)
(
"Original dates:"
)
(
datetime_series
)
2. Use dt.day to extract the day
(
"n=== Extract the day with dt.day ==="
)
days
=
datetime_series.
dt
.
day
(
"Day:"
)
(
days
)
3. Extract year, month, and day together
(
"n=== Extract year, month, and day ==="
)
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
}
)
(
df
)
4. Check how many days each month has
(
"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
(
pd.
DataFrame
(
{
'Month'
: dates_full
,
'Days'
: days_in_month
}
)
)
5. Days in February of a Leap Year
(
"n=== Days in February of a Leap Year ==="
)
leap_feb
=
pd.
Timestamp
(
'2024-02-01'
)
.
days_in_month
(
f
"Days in February 2024: {leap_feb}"
)
non_leap_feb
=
pd.
Timestamp
(
'2023-02-01'
)
.
days_in_month
(
f
"Days in February 2023: {non_leap_feb}"
)
Result:
=== 创建日期时间 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 an integer from 1 to 31 representing the day of the month.- You can extract the year, month, and day together to create a new DataFrame.
days_in_monthThe attribute retrieves the number of days in each month, which is useful for handling end-of-month dates.- 2024 is a leap year with 29 days in February; 2023 is a common year with 28 days in February.
Example 2: Filtering and Analysis by Day
Example
import
pandas
as
pd
import
numpy
as
np
Create a dataset containing dates
(
"=== 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 days
df
[
'day'
]
=
df
[
'date'
]
.
dt
.
day
(
df.
head
(
15
)
)
Filter records for specific days (such as the 15th of each month)
(
"n=== Transactions on the 15th of Each Month ==="
)
day_15
=
df
[
df
[
'day'
]
==
15
]
(
day_15
)
Filter the first half and second half of the month
(
"n=== First Half vs Second Half of the Month ==="
)
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'
]
(
half_stats
)
Aggregate by day
(
"n=== Average Revenue by Day ==="
)
daily_avg
=
df.
groupby
(
'day'
)
[
'revenue'
]
.
mean
(
)
.
round
(
2
)
(
daily_avg
)
Find the day with the highest revenue
(
"n=== Days with the Highest and Lowest Revenue ==="
)
max_day
=
df.
loc
[
df
[
'revenue'
]
.
idxmax
(
)
]
min_day
=
df.
loc
[
df
[
'revenue'
]
.
idxmin
(
)
]
(
f
"Highest revenue: {max_day['date'].date()}, amount {max_day['revenue']}"
)
(
f
"Lowest revenue: {min_day['date'].date()}, amount {min_day['revenue']}"
)
Result:
=== 创建交易数据 ===
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 group data by day for analysis.
- You can split the month into a first half and a second half for analysis.
idxmax()andidxmin()You can quickly find the record corresponding to an extreme value.
Example 3: Handling End-of-Month Dates
Example
import
pandas
as
pd
1. Handling the Last Day of Different Months
(
"=== Last Day of Each Month ==="
)
dates
=
pd.
date_range
(
'2023-01-01'
,
periods
=
12
,
freq
=
'MS'
)
(
"First day of each month:"
)
(
dates
)
Get the last day of each month
last_days
=
dates + pd.
offsets
.
MonthEnd
(
0
)
(
"nLast day of each month:"
)
(
last_days
)
2. Determine whether it is the end of the month
(
"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 (the end of the month)
'2023-02-28'
,
February 28 (non-leap year)
'2023-04-30'
,
April 30 (the 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
}
)
(
result
)
3. Handling Start-of-Month Dates
(
"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
(
result
)
4. Handling Inconsistent Month Lengths
(
"n=== Handling Inconsistent Month Lengths ==="
)
dates_to_check
=
pd.
Series
(
[
'2023-01-31'
,
Valid date
'2023-02-30'
,
Invalid date (February has no 30th day)
]
)
Attempt conversion and handle invalid dates
try
:
valid_dates
=
pd.
to_datetime
(
dates_to_check
,
errors
=
'coerce'
)
(
"Converted dates:"
)
(
valid_dates
)
(
"nDays Corresponding to Each Date:"
)
(
valid_dates.
dt
.
day
)
except
Exception
as
e:
(
f
"Error: {e}"
)
Result:
=== 各月最后一天 ===
First day of every month:
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)
Last day of the month:
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
=== 月份天数不一致的处理 ===
Converted date:
0 2023-01-31
1 NaT
Name: date, dtype: datetime64[ns]
Days corresponding to each date:
0 31.0
1 NaN
Code analysis:
is_month_endThe attribute can determine whether a date is the end of the month.is_month_startThe attribute can determine whether a date is the start of the month.pd.offsets.MonthEnd(0)It can retrieve the last day of the current month.- When handling invalid dates, you can use
errors='coerce'Convert invalid dates to NaT.
Notes
Important note:
Series.dt.day It can only be used with a Series of dtype datetime64.dt.days_in_month Get the number of days in each month.dt.day NaT is returned at the corresponding positions.
Common Pandas functions